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?

0

2 Answers 2

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 {
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.