'How to implement a method of a generic class?

TypeScript docs give the style for creating a generic class with generic methods as such:

class GenericNumber<NumType> {
  zeroValue: NumType;
  add: (x: NumType, y: NumType) => NumType;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
  return x + y;
};

But when I try to implement my own Generic class like so:

class GenClass<Gen> {
  func: <Gen>(a: Gen) => Gen;
}

let f = new GenClass<string>();
f.func = function(a: string) { 
  return a.repeat(5);
}

I get an error:

generics.ts:30:11 - error TS2339: Property 'repeat' does not exist on type 'Gen'.

30  return a.repeat(5);
             ~~~~~~

If I try annotating the a parameter:

let f = new GenClass<string>();
f.func = function(a: string) {
  return a.repeat(5);
}

I get a different error:

generics.ts:29:1 - error TS2322: Type '<Gen>(a: string) => any' is not assignable to type '<Gen>(a: Gen) => Gen'.
  Types of parameters 'a' and 'a' are incompatible.
    Type 'Gen' is not assignable to type 'string'.

29 f.func = function(a: string) {
   ~~~~~~

What am I doing wrong?



Solution 1:[1]

It turns out my problem was that in the definition of func, I was declaring a new type parameter, instead of reusing the one defined for the class. Should have done:

class GenClass<Gen> {
  func: (a: Gen) => Gen;
}

instead of:

class GenClass<Gen> {
  func: <Gen>(a: Gen) => Gen;
}

Thanks to @jonrsharpe for his comment!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Praise Dare