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

Nah*_*nde 2 typescript

我正在尝试在打字稿中构建一个类,其中所有函数都必须返回一个承诺而不显式声明每个函数的返回类型换句话说,向类添加非异步函数应该抛出一个错误,即

class myClass {
    errfunc() { // This should throw a compiler error
        return 1;
    }

    correctfunc() {
        return new Promise((res) => res('success')) // This should work correctly
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了以下

interface PromiseDictionary {
    [key: string]: () => Promise<any>;
}
class myClass implements PromiseDictionary {
    a() {
        return new Promise(res => res('success'))
    };
}
Run Code Online (Sandbox Code Playgroud)

但它抛出以下错误:

Class 'myClass' incorrectly implements interface 'PromiseDictionary'.
Index signature is missing in type 'myClass'.`
Run Code Online (Sandbox Code Playgroud)

如何才能做到这一点?

Tit*_*mir 5

您可以说该类使用当前类型的键实现了一个记录,() => 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)