[英]Typescript: Generic Type uses Extends keyword instead of Implements with interface
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. 但是,在使用泛型类型时,必须使用extends
来表示对象必须实现接口。
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. 使用的implements
,使我更有意义。
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
. 这就是这里发生的情况:当编写U extends ITest
,就是说泛型U
扩展了ITest
类型。
Furthermore, in TypeScript, when you define a class: 此外,在TypeScript中,当您定义类时:
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. ...实际上是在指定两件事:首先,您要声明一些代码(标准构造函数),其次,您指定了一个名为Foo
的类型,可以将其用作接口,因为那几乎是什么。 (In a certain sense, a class is just an interface plus some code.) (从某种意义上说,一个类就是一个接口加上一些代码。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.