jeanpaul62
jeanpaul62

Reputation: 10571

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.

And finally, I want to create a function that is flyIn2Seconds, which looks like this:

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

However any extends CanFly doesn't work ([ts] '?' expected.). Is there a way to specify the type "any class that implements CanFly"?

Upvotes: 0

Views: 49

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074809

You simply specify the interface:

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

More in the interfaces documentation.

Upvotes: 2

Related Questions