Can You Specify Multiple Type Constraints For TypeScript Generics Can You Specify Multiple Type Constraints For TypeScript Generics typescript typescript

Can You Specify Multiple Type Constraints For TypeScript Generics


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


A work around for this would be to use a super-interface (which also answers the question "why would you allow an interface to inherit from a class").

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


Ref the comment about an interface deriving from a class...whats in a name?

I found this in section 3.5 of the 0.9.0 spec:

Interface declarations only introduce named types, whereas class declarations introduce named types and constructor functions that create instances of implementations of those named types. The named types introduced by class and interface declarations have only minor differences (classes can’t declare optional members and interfaces can’t declare private members) and are in most contexts interchangeable. In particular, class declarations with only public members introduce named types that function exactly like those created by interface declarations.