我正在尝试在Typescript中构建一个类,其中所有函数都必须返回一个Promise,而无需显式声明每个函数的返回类型。换句话说,向该类添加一个非异步函数应该抛出一个错误,即
class myClass {
errfunc() { // This should throw a compiler error
return 1;
}
correctfunc() {
return new Promise((res) => res('success')) // This should work correctly
}
}
我尝试了以下
interface PromiseDictionary {
[key: string]: () => Promise<any>;
}
class myClass implements PromiseDictionary {
a() {
return new Promise(res => res('success'))
};
}
但这会引发以下错误:
Class 'myClass' incorrectly implements interface 'PromiseDictionary'.
Index signature is missing in type 'myClass'.`
如何才能做到这一点?
您可以说该类使用当前类型的键来实现记录,() => Promise<any>
这将强制所有公共成员成为返回a的函数Promise
:
class myClass implements Record<keyof myClass, () => Promise<unknown>> {
errfunc() { // This should throw a compiler error
return 1;
}
correctfunc() {
return new Promise((res) => res('success')) // This should work correctly
}
}
这将强制所有功能都没有参数,从而允许具有参数的功能可以使用
class myClass implements Record<keyof myClass, (...a: never[]) => Promise<unknown>> {
errfunc() { // This should throw a compiler error
return 1;
}
correctfunc(a: string) {
return new Promise((res) => res('success')) // This should work correctly
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句