简体   繁体   English

TypeScript:检查派生类是否实现方法

[英]TypeScript: Check if derived class implements method

I got two classes, one deriving from the other, and on the base class I need to check if the derived class is implementing a method with a specific name: 我有两个类,一个派生自另一个,在基类上我需要检查派生类是否正在实现具有特定名称的方法:

class Foo {
    constructor() { }

    childHasMethod() {
        if(this.method) {
            console.log('Yay');
        } else {
            console.log('Nay');
        }
    }
}

class Bar extends Foo {
    constructor() {
        super();
        this.childHasMethod();
    }

    method() {

    }
}

var bar = new Bar();

Even though the line if(this.method) { is marked red on the playground, it works. 即使行if(this.method) {在操场上标记为红色,它也可以。 But the local compiler throws a compilation error: The property 'method' does not exist on value of type 'Foo' . 但是本地编译器抛出了一个编译错误: The property 'method' does not exist on value of type 'Foo'

Is there a clean way to achieve what I'm trying to do? 是否有一种干净的方式来实现我想要做的事情?

In order to "sneak it past the compiler" you can treat this as dynamic: 为了“通过编译器偷偷摸摸”,您可以将this视为动态:

(<any>this).method

I have made a full example of this on the TypeScript Playground . 我在TypeScript Playground上做了一个完整的例子。

childHasMethod() {
    if((<any>this).method) {
        alert('Yay');
    } else {
        alert('Nay');
    }
}

Having said this, having a base class know details about its sub-classes could get you into tricky places. 说到这一点,让一个基类知道它的子类的细节可能会让你进入棘手的地方。 Usually I would try to avoid this as it sounds like the specialisations are leaking into the base class - but you may have a particular thing you are doing and know your program better than me so I'm not saying "don't do this" - just "are you sure" :) 通常我会尽量避免这种情况,因为它听起来像专业化渗透到基类 - 但你可能有一个特定的事情,你比我更了解你的程序所以我不是说“不要这样做” - 只是“你确定”:)

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

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