How can you put a constraint on a TypeScript type parameter. In c# you can use the construct { where T:class}?
-
Take a look herePajdziu– Pajdziu2015-11-05 22:57:21 +00:00Commented 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.Alexei - check Codidact– Alexei - check Codidact2019-02-15 12:33:23 +00:00Commented 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).jhpratt– jhpratt2019-02-16 00:38:55 +00:00Commented Feb 16, 2019 at 0:38
Add a comment
|
1 Answer
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.
1 Comment
Tarhuna Em
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.