Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript type parameter to implement multiple interfaces

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> { }
like image 406
Matt Avatar asked Jul 18 '15 11:07

Matt


People also ask

Can you implement multiple interfaces in TypeScript?

Typescript allows an interface to inherit from multiple interfaces.

What is type T in TypeScript?

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.

How do you pass an interface as a parameter TypeScript?

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.

How do I combine two TypeScript interfaces?

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.


2 Answers

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> { }
like image 72
Alex Avatar answered Oct 22 '22 11:10

Alex


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.

like image 40
Herrington Darkholme Avatar answered Oct 22 '22 11:10

Herrington Darkholme