123

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?

0

3 Answers 3

154

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Union types are a great way to achieve this as you don't need to create an interface for the sole purpose of the constraint. They didn't exist back in 2013 - but this is definitely how I'd recommend doing it now.
This answer is wrong. Union types don't have the same semantics as extending two distinct types at all.
@AlexG Sure this is not the same as extending two types but the same as implementing two interfaces.
41

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

1 Comment

This is the right solution. Extending an interface from two classes is kind of scary, though -- if both declare private members, the interface is unfulfillable
1

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.

1 Comment

Optional class members are now implemented: github.com/Microsoft/TypeScript/pull/8625

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.