我正在尝试构建一个在构造函数阶段构建一些动态方法的类,一切正常,但 VS Code 自动建议不适用于动态方法?我们应该怎么做? 这是 codeSandBox
我也试过 interface
但还是不行
export default class A {
private version = 1;
get getVersion() {
return this.version;
}
private actions = ["approve", "edit", "delete"];
constructor() {
this.actions.forEach(
method =>
(A.prototype[method] = route => {
console.warn(method + " called");
})
);
}
}
const B = new A();
console.warn(B.getVersion);
console.warn(B.approve()) // auto suggestion not available here
最佳答案
你可以做到这一点......但它真的很hacky。像这样的元编程不可能完全类型检查。这是一个 playground使用此解决方案。
首先告诉TS,actions是一个常量数组,这样可以缩小类型。
private actions = ["approve", "edit", "delete"] as const;
接下来,创建一个映射类型,描述您的 forEach
方法添加到该类型的内容。
type _A = {
[K in A['actions'][number]]: (route: string) => void
}
请注意,这必须是一个类型
。它不能是一个接口(interface)
。
最后,添加一个扩展这个类型别名的接口(interface)。我原以为 TS 会在这里对我大喊大叫,但显然这没关系。
export default interface A extends _A {
}
关于javascript - typescript 类型的动态类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59256430/