可以在运行时在TypeScript中检测到重写的方法吗?

时间:2017-07-18 10:37:30

标签: typescript reflection

E.g。有可能做这样的事吗?..

export default class SuperClass {
    public method(): void {
        /* noop */
    }
}

export default class SubClass extends SuperClass {
    public method(): void {
        /* useful work */
    }
}


export default class SmallerClass extends SuperClass {

}

let a = new SubClass();
let b = new SmallerClass();

/* Something like this?.. */
a.overrides("method") => true;
b.overrides("method") => false;

1 个答案:

答案 0 :(得分:2)

您可以这样做:

class SuperClass {
    public method(): void {
        /* noop */
    }

    public overrides(methodName: string): boolean {
        return typeof SuperClass.prototype[methodName] === "function"
            && SuperClass.prototype[methodName] !== this[methodName];
    }
}