假设我有5个简化函数,首先将Api
用于进行调用的对象作为参数,将第二个(可选)参数作为api调用本身的参数。
// functions.ts
function f1 (api: Api) {
return () => { // returns a Promise<string> }
}
// some other functions
function f5 (api: Api) {
return (id: number) => { // returns a Promise<number> }
}
现在,我想创建一个具有这种类型的对象:
{
f1: () => Promise<string>
// ...
f5: (id: number) => Promise<number>
}
这是我所做的:
import * as functions from './functions';
const api = new Api(); // Define the Api object here
const withApi = Object.keys(functions).reduce((result, key) => {
result[key as keyof typeof functions] = functions[key as keyof typeof functions](api)
}, {} as /* What type should i put here??? */);
我能找到的最好的东西/* What type should i put here??? */
是{ [index:string]: Promise<any> }
,这根本不能令人满意。
您可以创建一个映射类型,该类型将包含原始函数对象中所有键的键,但它们的类型与每个函数的返回类型相同(使用条件类型提取ReturnType<T>
)
type AllReturnTypes<T extends Record<keyof T, (...a: any) => any>> = {
[P in keyof T]: ReturnType<T[P]>
}
const withApi = Object.keys(functions).reduce((result, key) => {
result[key as keyof typeof functions] = functions[key as keyof typeof functions](api)
return result;
}, {} as AllReturnTypes<typeof functions>);
withApi.f1();
withApi.f5(10);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句