Search code examples
typescripttypescript-generics

Can You Specify Multiple Type Constraints For TypeScript Generics


I have a generic interface like this example with a single type constraint:

export interface IExample<T extends MyClass> {
    getById(id: number): T;
}

Is it possible to specify multiple type constraints instead of just one?


Solution

  • Typescript doesn't allow the syntax <T extends A, B> in generic constraints. However, you can achieve the same semantics by the intersection operator &:

    interface Example<T extends MyClass & OtherClass> {}
    

    Now T will have properties from both MyClass and OtherClass.