Promise.all的类型定义与文档不匹配 [英] Type definition of Promise.all doesn't match with the docs

查看:113
本文介绍了Promise.all的类型定义与文档不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看类型定义的Promise.all 中,我看到10个定义:

Looking at the type definition of Promise.all, I see 10 definitions:

/**
 * Creates a Promise that is resolved with an array of results when all of the provided Promises
 * resolve, or rejected when any Promise is rejected.
 * @param values An array of Promises.
 * @returns A new Promise.
 */
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;

我只包含了一个长度为3的数组,但是还存在all<T1>all<T1, T2>,一直到all<T1, T2, ..., T9, T10>.

I only included the one with an array of length 3, but there also exist all<T1>, all<T1, T2>, all the way up to all<T1, T2, ..., T9, T10>.

但是,这与Promise.all的实现不匹配,Promise.all的实现可以将长度大于10的数组作为输入:

However, this doesn't match with the implementation of Promise.all, which can take as an input an array longer than 10:

let myPromise = num => Promise.resolve(num);
let myPromisesArray = (new Array(20))
  .fill()
  .map((_,i) => myPromise(i));
Promise.all(myPromisesArray).then(console.log)

我不是世界上最糟糕的开发人员,但我仍然假设,产生ES2015类型定义的Microsoft开发人员比我更了解JS/TS,这引出了一个问题:

I'm not the worst developer in the world but still, I make the assumption that the Microsoft developers who produced the type definition of ES2015 know more about JS/TS than me, which begs the question:

为什么Promise.all的类型定义与其文档还是其实现?

推荐答案

最多10种类型的泛型声明仅考虑非均匀的元组",即不同索引具有显式独立类型的数组.

The generic declaration up to 10 types is only accounting for non-uniform "tuples", or arrays where different indices have explicit independent types.

还有声明支持无限长度的统一类型数组:

all<T>(values: (T | PromiseLike<T>)[]): Promise<T[]>;

使用长度最大为10的元组的声明应涵盖合理数量的用例,并且由于TypeScript作为一种语言的局限性所致,因为元组的泛型类型推断是a的统一数组包含联盟类型,该类型将使用上面的签名.这种类型的泛型声明,直至非均匀类型的任意界限,在其他语言(例如C#)中也很常见.例如, Action<> Func<> 限制使用16种参数类型.

The declarations using a tuple of up to length 10 are supposed to cover a reasonable amount of use-cases, and are due to a limitation of TypeScript as a language, since generic type inference for a tuple is a uniform array of an encompassing union type, which would use the signature above. These sort of generic declarations up to an arbitrary bound of non-homogeneous types are common-place in other langauges like C# as well. For example, Action<> and Func<> use a limit of 16 parameter types.

这篇关于Promise.all的类型定义与文档不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆