Can You Specify Multiple Type Constraints For TypeScript Generics

Fenton picture Fenton · Jun 15, 2013 · Viewed 35.9k times · Source

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?

Answer

STO picture STO · Aug 11, 2016

Typescript doesn't offer a syntax to get multiple inheritance for generic types. However, you can achieve similar semantics by using the Union types and Intersection types. In your case, you want an intersection :

interface Example<T extends MyClass & OtherClass> {}

For a Union of both types :

interface Example<T extends MyClass | OtherClass> {}