Can You Specify Multiple Type Constraints For TypeScript Generics

TypescriptTypescript Generics

Typescript Problem Overview


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?

Typescript Solutions


Solution 1 - Typescript

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

Solution 2 - Typescript

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

Solution 3 - Typescript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFentonView Question on Stackoverflow
Solution 1 - TypescriptSTOView Answer on Stackoverflow
Solution 2 - TypescriptFentonView Answer on Stackoverflow
Solution 3 - TypescriptandyksView Answer on Stackoverflow