How can you put a constraint on a TypeScript type parameter. In c# you can use the construct { where T:class}
?
Does Typescript support constraints on type parameters like c# { where T:class}.
Yes. Syntax is of the form <T extends SomeClass>
instead of <T>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With