Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - Check if Class implements an Interface

Tags:

typescript

I'm using an interface in TypeScript to define a function that is only available on some of the classes that extend the base class. This is a simplified version of the code I have so far:

class Animal { }  interface IWalkingAnimal {     walk(): void; }  class Dog extends Animal implements IWalkingAnimal { }  class Cat extends Animal implements IWalkingAnimal { }  class Snake extends Animal { }  private moveAnimal(animal: Animal) {     if (animal instanceof Cat || animal instanceof Dog) {         animal.walk();     } } 

Now, the trouble is I'll be adding more 'walking' animals so the moveAnimal functional will grow too large to be manageable. What I would like to do is something like this:

private moveAnimal(animal: Animal) {     if (animal implements IWalkingAnimal ) {         animal.walk();     } } 

However the 'implements' check does not work, and I cannot find an equivalent to 'instanceof' when using interfaces. In Java it seems that the use of 'instanceof' would work here, but TypeScript will not allow this.

Does such a thing exist in TypeScript, or is there a better approach here? I am using the TypeScript 1.8.9.

like image 952
MarkLunney Avatar asked May 31 '16 10:05

MarkLunney


People also ask

How do you check if a class is an interface?

isInterface() method The isArray() method of the Class class is used to check whether a class is an interface or not. This method returns true if the given class is an interface. Otherwise, the method returns false , indicating that the given class is not an interface.

Which keyword is used to check if a class satisfies a particular interface in TypeScript?

Here's another option: the module ts-interface-builder provides a build-time tool that converts a TypeScript interface into a runtime descriptor, and ts-interface-checker can check if an object satisfies it.

Which keyword is used to check if a class satisfies a particular interface?

We used a user-defined type guard to check if an object implements an interface.


1 Answers

Unlike classes, interfaces exist only at compile-time, they are not included into the resulting JavaScript, so you cannot do an instanceof check.

You could make IWalkingAnimal a subclass of Animal (and use instanceof), or you could check if the object in question has a walk method:

if (animal['walk']) {} 

You can wrap this in a user defined type guard (so that the compiler can narrow the type when used in an if statement, just like with instanceof).

/** * User Defined Type Guard! */ function canWalk(arg: Animal): arg is IWalkingAnimal {    return (arg as IWalkingAnimal).walk !== undefined; }   private moveAnimal(animal: Animal) {     if (canWalk(animal)) {         animal.walk();  // compiler knows it can walk now     } } 
like image 101
Thilo Avatar answered Oct 14 '22 09:10

Thilo