假设我有一些函数,比如:
function allPromises<T>(array: Promise<T>[]): Promise<T[]> {
return Promise.all(array);
}
(注:这是有意设计为最低限度的复制)
如果我这么做了,效果很好:
const p1: Promise<string> = new Promise((resolve) => resolve('1'));
const p2: Promise<string> = new Promise((resolve) => resolve('2'));
const test1 = [p1, p2];
const res1 = allPromises(test1);
没有输入错误,res1
正确输入为Promise<string[]>
;
但如果我这么做了:
const p1: Promise<string> = new Promise((resolve) => resolve('1'));
const p2: Promise<number> = new Promise((resolve) => resolve(2));
const test2 = [p1, p2];
const res2 = allPromises(test2);
现在我接到TS投诉:
类型为"(Promise<;string>;|Promise<;number>;)的参数[]不可分配给"Promise"类型的参数<;字符串>;[]'.
这似乎是因为test2
被输入为(Promise<number> | Promise<string>)[]
我可以通过以下方式解决这个问题:
const test2: Promise<string | number>[] = [p1, p2];
然后res2
正确地被输入为Promise<(string | number)[]>
但是,有没有一种方法可以键入我的函数,这样它就可以正确地推断出类型,而不是强迫我以这种方式显式地声明数组的类型?
注意:我也try 过重载函数,类似于Promise.all
键入的方式,但它也失败了,需要我显式键入数组,以便TS接受它:
function allPromises<T1, T2>(array: [Promise<T1>, Promise<T2>]): Promise<[T1, T2]>
function allPromises<T>(array: Promise<T>[]): Promise<T[]>
function allPromises(array: Promise<unknown>[]): Promise<unknown[]> {
return Promise.all(array);
}
这种超负荷也没有帮助:
function allPromises<T1, T2>(array: (Promise<T1> | Promise<T2>)[]): Promise<(T1 | T2)[]>
我希望在TS V3中实现这一点...我在V4中看到了一些新类型.5+对这一点很有用,但我暂时还停留在V3中.