For example, the collection -

class Collection { insert(node){ } swap(a, b){ // в этом методе я должен обращаться // к свойствам node.someProps } } 

And with generics .ts it will be approximately like this

 class Collection<T> { public insert<T>(node: T): void { } public swap<T>(a: T, b: T): void{ // в этом методе я должен обращаться // к свойствам node.someProps // !!! НО !!! } } 

... BUT I can't do that, because type T no someProps property.
The question is how to make a dynamic collection with a base type that will have the necessary properties? Yes, and I would like to return the final type, not the base type.

Here is an example on TypeScript Playground .

  • Obviously on ruSO this label is not very popular :-) - Grundy

2 answers 2

Since the class is already generic, you do not need to specify this for functions.

To determine the limitations, you can use the example from the help

 interface BaseNode { someProps: number; } class Collection<T extends BaseNode> { swap(a: T, b: T): void { let value = a.someProps; // T extends BaseNode, so have someProps } } 

Example

  • I also waited while I decided to try it again with extends and surprisingly it happened the second time :) Thank you. - Ivan Petrov
  • @IvanPetrov, note also that the generic function itself is removed and the type definition from the class is used, if you return it to the swap<T> function - then everything will break again because the extends function types will not be spelled out - Grundy
  • Yes Yes! If you apply a generic on a method, then you have to write extends . - Ivan Petrov

It is necessary to prescribe a restriction on type T :

 interface BaseNode { someProps: any; } class Collection<T extends BaseNode> { swap(a: T, b: T): void { let value = a.someProps; } } 

Or, if the extra interface does not want to start:

 class Collection<T extends { someProps: any; }> { swap(a: T, b: T): void { let value = a.someProps; } } 
  • not exactly the right example turned out, T not used anywhere, and in BaseNode this field was available - Grundy