简体   繁体   English

TypeScript - 检查 Class 是否实现了接口

[英]TypeScript - Check if Class implements an Interface

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.我在 TypeScript 中使用一个接口来定义一个函数,该函数仅在扩展基类的某些类上可用。 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.现在,问题是我将添加更多“行走”动物,因此 moveAnimal 函数会变得太大而无法管理。 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.但是,“实现”检查不起作用,并且在使用接口时我找不到与“instanceof”等效的东西。 In Java it seems that the use of 'instanceof' would work here, but TypeScript will not allow this.在 Java 中,'instanceof' 的使用似乎可以在这里工作,但 TypeScript 不允许这样做。

Does such a thing exist in TypeScript, or is there a better approach here? TypeScript 中是否存在这样的东西,或者这里有更好的方法吗? I am using the TypeScript 1.8.9.我正在使用 TypeScript 1.8.9。

Unlike classes, interfaces exist only at compile-time, they are not included into the resulting JavaScript, so you cannot do an instanceof check.与类不同,接口仅在编译时存在,它们不包含在生成的 JavaScript 中,因此您无法进行instanceof检查。

You could make IWalkingAnimal a subclass of Animal (and use instanceof ), or you could check if the object in question has a walk method:您可以使IWalkingAnimal成为 Animal 的子类(并使用instanceof ),或者您可以检查所讨论的对象是否具有walk方法:

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 ).您可以将其包装在用户定义的类型保护中(以便编译器在if语句中使用时可以缩小类型,就像使用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
    }
}

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

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