我有一个函数,它接受一个对象,其中每个属性都是一个承诺。它等待所有的承诺完成,然后返回一个新的对象,该对象具有相同的属性,但现在已解析了值。
resolved_props.company
应该是string
,而不是Promise<string>
// TODO: fix the types on this
function promise_props<T>(obj:T):Promise<T> {
const keys = Object.keys(obj)
const len = keys.length
const awaitables = new Array<T>(len)
for (var i = 0; i < len; i++) awaitables[i] = (obj as any)[keys[i]]
return Promise.all(awaitables).then((results) => {
const byName:any = {}
for (var i = 0; i < len; i++) byName[keys[i]] = results[i]
return byName
})
}
3条答案
按热度按时间zaqlnxep1#
typescript 4.5
实用程序类型
Awaited
正式内置于typescript v4.5中。https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/#awaited-type
bf1o4zei2#
您的类型不够准确,TypeScript编译器无法判断它们此时是否是承诺的类型。
你需要的是这样的东西:
但只有当你的对象有相同类型的承诺时,它才会起作用,例如:
我不确定在当前的TypeScript版本中是否有可能让它与各种承诺类型一起工作,但正如Tao所建议的,您可以使用TypeScript 2.8中的新特性来让它工作:
正如你所看到的,返回类型被正确地推断出来了。我认为方法的实现可以改进。我找不到一种方法来示例化返回类型的示例并使用
any
,但是尽管编译器不能推断它,它是类型安全的,因为我们解决了所有的承诺。bfhwhh0e3#
在typescript 2.8之后,我能够使用以下策略
用法如下