In C#, I can do this:
class Dictionary<TKey, TVal> where TKey : IComparable, IEnumerable { }
Is there a way in TypeScript 1.5 beta for a type parameter in a generic class or function to implement multiple interfaces, without creating an entirely new interface for the purpose?
The obvious way is obviously not working due to the ambiguity of commas.
class Dictionary<TKey extends IComparable, IEnumerable, TValue> { }
By the way, funnily enough, extends
can handle interface unions perfectly fine in generics:
class Dictionary<TKey extends IComparable|IEnumerable, TValue> { }
Typescript allows an interface to inherit from multiple interfaces.
This article opts to use the term type variables, coinciding with the official Typescript documentation. T stands for Type, and is commonly used as the first type variable name when defining generics. But in reality T can be replaced with any valid name.
An interface type cannot be passed as a parameter. When running TypeScript code, you are really compiling it down to JavaScript and then running the JavaScript. An interface is a TypeScript compile-time construct, so at runtime, there is no such thing as an interface type to call functions on or inspect properties of.
To merge two interfaces with TypeScript, we can use extends to extend multiple interfaces. to create the IFooBar that extends IFoo and IBar . This means IFooBar has all the members from both interfaces inside.
Intersection types are now here since TS 1.6 and you can use it like this in your above example:
class Dictionary<TKey extends IComparable & IEnumerable, TValue> { }
In TS1.5, the only way you can do that is declare a new interface which extends A and B, sadly.
Another alternative is praying for the coming TS1.6 where intersection type is supported.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With