Reputation: 7772
From what I understand, an object can implement an interface and an object can extend a class.
However, when using generic type, one must use extends
to say that the object must implements the interface.
Ex:
interface ITest {
a:number;
}
function myF1<U extends ITest>(a:U){} //valid
function myF2<U implements ITest>(a:U){} //error
Is there a reason for this inconsistency? The use of implements
makes more sense to me.
Upvotes: 1
Views: 324
Reputation: 11740
an object can implement an interface and an object can extend a class
A class can implement an interface, and a class can extend a class. An interface can also extend an interface (that is, a type can extend a type), which is consistent with classes extending other classes. And that's what's happening here: when you write U extends ITest
, you are saying that the generic type U
extends the type ITest
.
Furthermore, in TypeScript, when you define a class:
class Foo {}
...you are actually specifying two things: first, you are saying that you want some code (the standard constructor function), and second, you are specifying a type called Foo
, which you can use as if it were an interface, because that's pretty much what it is. (In a certain sense, a class is just an interface plus some code.)
Upvotes: 4