1

I'm attempting to declare a TypeScript class with a constrained generic parameter. In C#, the following would compile:

public class NewClass<T> where T: BaseClass {
}

What is the TypeScript equivalent?

theMayer
  • 15,456
  • 7
  • 58
  • 90

2 Answers2

4

You're looking for the extends keyword. You can use it right after the generic parameter to constrain it to be a subtype of the specified type.

So the equivalent for your example would be:

class NewClass<T extends BaseClass> {
    // Things...
}

You can read more about generic constraints in the documentation here.

CRice
  • 29,968
  • 4
  • 57
  • 70
  • Rant: I found the documentation on Generics, and on TypeScript in general, to be very difficult to parse. Which is why I ultimately posted the question - if you visit the c# page, it is extremely easy to tell how to do this. Not true in TypeScript. – theMayer May 14 '18 at 20:57
4

For both classes and interfaces as base, you have to constrain T like this:

export class NewClass<T extends BaseClass> {
}

While you derive classes from interfaces with implements, the same is not true for generic constraints, making this code possible:

export class NewClass<T extends BaseInterface> implements BaseInterface {
}
Sefe
  • 13,731
  • 5
  • 42
  • 55