【发布时间】:2021-06-25 00:00:32
【问题描述】:
我正在尝试编写一个函数来解析对象的所有 Promise 值:
const resolveObject = async (obj) => // pure JavaScript implementation
Object.fromEntries( // turn the array of tuples with key-value pairs back into an object
(await Promise.all(Object.values(obj))).map((el, i) => [ // Promise.all() the values, then create key-value pair tuple
Object.keys(obj)[i], // tuple contains the original object key
el, // tuple contains the resolved object value
]) // zips the split key/value arrays back into one object
);
实施工作正常。下面是一个使用示例:
/* example input */
const exampleInput = { // <- { foo: Promise<string>, bar: Promise<{ test: number }>, baz: boolean }
foo: Promise.resolve("Hello World"),
bar: Promise.resolve({
test: 1234
}),
baz: false
}
const expectedOutput = resolveObject(exampleInput) // <- { foo: string, bar: { test: number }, baz: boolean }
/* expected output: strongly typed object with same keys and no Promise<> wrappers in signature */
这就是事情开始崩溃的地方。我期待一个具有与输入相似签名的强类型输出(只是没有 Promise 包装器),但相反,我得到以下通用对象输出:
Promise<{ [k: string]: unknown; }>
于是我开始给resolveObject函数添加类型注解:
const resolveObject = async <T>(
obj: { [K in keyof T]: Promise<T[K]> }
): Promise<{ [K in keyof T]: T[K] }> => { ... }
现在我收到一个类型转换错误:type '{ [k: string]: unknown; }' is not assignable to type '{ [K in keyof T]: T[K]; }'
我对 TypeScript 还很陌生,真的不知道下一步该做什么(我知道如何诊断错误消息,但我很确定我的类型注释/函数签名有问题)。我怎样才能实现我正在寻找的东西?
【问题讨论】:
标签: javascript typescript object types