简体   繁体   English

TypeScript:任何实现特定接口的类

[英]TypeScript: Any class that implements a particular interface

Let's say I have this interface 假设我有这个介面

interface CanFly {
  fly(): void;
}

And I will create two classes, Bird and AirPlane that both implement the above interface. 我将创建两个类,即BirdAirPlane ,这两个类均实现上述接口。

And finally, I want to create a function that is flyIn2Seconds , which looks like this: 最后,我想创建一个函数flyIn2Seconds ,如下所示:

function flyIn2Seconds(who: any extends CanFly) {
  setTimeout(() => who.fly(), 2000);
}

However any extends CanFly doesn't work ( [ts] '?' expected. ). 但是, any extends CanFly都无法正常工作( [ts] '?' expected. )。 Is there a way to specify the type "any class that implements CanFly"? 有没有一种方法可以指定类型“任何实现CanFly的类”?

You simply specify the interface: 您只需指定接口:

function flyIn2Seconds(who: CanFly) {
  setTimeout(() => who.fly(), 2000);
}

More in the interfaces documentation . 接口文档中有更多内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM