Search code examples
typescripttype-constraints

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}?


Solution

  • 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.