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 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.
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.