Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript generic constraints on type parameters class

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

like image 739
Tarhuna Em Avatar asked Sep 26 '22 07:09

Tarhuna Em


1 Answers

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.

like image 196
basarat Avatar answered Oct 01 '22 16:10

basarat