3

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. But the local compiler throws a compilation error: The property 'method' does not exist on value of type 'Foo'.

Is there a clean way to achieve what I'm trying to do?

4

1 回答 1

1

为了“偷偷溜过编译器”,您可以将this其视为动态:

(<any>this).method

我在TypeScript Playground上做了一个完整的例子。

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

话虽如此,让基类了解其子类的详细信息可能会让您进入棘手的地方。通常我会尽量避免这种情况,因为听起来专业化正在泄漏到基类中 - 但您可能正在做某件事并且比我更了解您的程序,所以我不是说“不要这样做” - 只是“你确定” :)

于 2013-11-08T08:52:07.577 回答