6

How can you put a constraint on a TypeScript type parameter. In c# you can use the construct { where T:class}?

3
  • Take a look here Commented Nov 5, 2015 at 22:57
  • This seems like a valid question to me and the answer is exactly what people coming from .NET / Java etc. expect to have in TypeScript. Voting to reopen. Commented Feb 15, 2019 at 12:33
  • Agree with @Alexei. No idea why this was closed as a request for an off-site resource (unanimously, at that). Commented Feb 16, 2019 at 0:38

1 Answer 1

5

Does Typescript support constraints on type parameters like c# { where T:class}.

Yes. Syntax is of the form <T extends SomeClass> instead of <T>

Example

interface Foo{
    foo: number;
}

function foo<T extends Foo>(foo:T){
    console.log(foo.foo);
}

foo({foo:123}); // okay
foo({foo:'123'}); // Error

Note that types in typescript are structural (why) which means that classes and interfaces are handled the same way as far as the generic constraint is concerned.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Basarat for your answer, seen your collection and online resource before which are very helpful and thanks again for your help, most of classes derived from one class Entity, your suggestion will save me lots of time.

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.