gpt4 book ai didi

typescript - 强制Typescript中类中所有函数的返回类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:21 25 4
gpt4 key购买 nike

我正在尝试在 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>这将强制所有公共(public)成员成为返回 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
}
}

play

这将强制所有函数都没有参数,以允许您可以使用带参数的函数

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
}
}

play

关于typescript - 强制Typescript中类中所有函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57624479/

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