javascript - 是否可以在运行时迭代 Typescript 类抽象方法?

标签 javascript typescript oop

我需要知道该类的抽象方法列表(实际上包括抽象方法在内的所有方法)。是否可以使用 Typescript 以某种方式进行?

export abstract class INotificationService {
     abstract dismissRequested();
}

console.log(Object.getMethodsList(INotificationService));

预期结果:['dismissRequested', ...]

最佳答案

没有为抽象方法生成代码,因此没有直接获取方法的方法。您可以创建一个虚拟实现并从中获取函数:

abstract class INotificationService {

    abstract dismissRequested(): void;
}

function getMethods<T>(cls: new (...args: any[]) => T): string[] {
    return Object.getOwnPropertyNames(cls.prototype).filter(c=> c!=="constructor");
}

var methods = getMethods<INotificationService>(class extends INotificationService {
    dismissRequested(): void {
        throw new Error("Method not implemented.");
    }
});

如果我们愿意,我们可以通过禁止虚拟实现类拥有任何新方法来使它更安全一些。这将防止我们忘记我们从抽象类中删除的旧方法,尽管虚拟实现可能会覆盖非抽象的现有类方法,因此请谨慎使用:

type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T];
function getMethods<T>(): <TResult>(cls: new (...args: any[]) => TResult & { [ P in Diff<keyof TResult, keyof T>]: never }) => string[] {
    return cls => Object.getOwnPropertyNames(cls.prototype).filter(c=> c!=="constructor");
}

abstract class INotificationService {

    abstract dismissRequested(): void;
    nonAbstarct(): void {}
}
var methods = getMethods<INotificationService>()(class extends INotificationService {
    // Implement abstract methods, although it is possible to add other methods as well and the compiler will not complain 
    dismissRequested(): void {
        throw new Error("Method not implemented.");
    }
});


// Will cause an error
var methods2 = getMethods<INotificationService>()(class extends INotificationService {
    dismissRequested(): void {
        throw new Error("Method not implemented.");
    } 
    oldDismissRequested(): void {
        throw new Error("Method not implemented.");
    }
});
// Will NOT cause an error
var methods3 = getMethods<INotificationService>()(class extends INotificationService {
    dismissRequested(): void {
        throw new Error("Method not implemented.");
    } 
    nonAbstarct(): void {
        throw new Error("Method not implemented.");
    }
});

关于javascript - 是否可以在运行时迭代 Typescript 类抽象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49487176/

相关文章:

javascript - 如何更改 moment.js 的语言?

JavaScript 2D 数组为空时推送

javascript - 疯狂需要启用跨站点脚本

javascript - Angular 4 中可能存在竞争条件吗

javascript - Material-UI 中的 DefaultTheme 导致 `Invalid module name in augmentation` 错误

c++ - 抽象类——C++实践中的隐藏实现

javascript - d3 js可以扩展多少

javascript - 带有 Firebase 数据的 Angular 应用程序 : why am I seeing data from the previous page?

delphi - 开发新代码时是否应该使用类助手?

objective-c - OOP:设计菜单系统