gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:39:06 25 4
gpt4 key购买 nike

我需要知道该类的抽象方法列表(实际上包括抽象方法在内的所有方法)。是否可以使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com