15

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

2 Answers 2

24

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> { }
Sign up to request clarification or add additional context in comments.

6 Comments

This is not exactly the same as extending both interfaces. It works in these simple cases though, where the interfaces have no overlap.
@AlexG What do you mean? Why would overlapping interfaces be a problem?
With { a: number } & { a: string } the resulting type would silently be the same as { a: number & string } Which is not the same as inheriting from two distinct interfaces, where a conflicting property would raise an error.
@AlexG Ok, we are taking about two different things here. In this case, we say that the type extends from other types. The intersection type of { a: number } & { a: string } is obviously the same as { a: number & string }, nothing strange here. However if you are talking about class inheritance, then of course we will have conflicts, but this will never happen in TS since it does not have multiple inheritance.
Oh, and some ambiguities. You don't inherit from interfaces, you implement them. And there is no conflict for a class to implement both { a: number } and { a: string }, you just have to make sure that the member a of the class is both a number and a string (and that is the intersection type number & string).
|
2

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.

Comments

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.