我正在为项目使用TypeScript,在Promise.all(...)
某些情况下需要使用,它返回许多项目的数组:
Promise.all(
firstRequest,
secondRequest,
...,
nthRequest
)
.then((array : [FirstType, SecondType, ..., NthType]) => {
// do things with response
});
现在,由于类型[FirstType, SecondType, ..., NthType]
太长而无法在此处定义,因此我想在其他地方定义它并在那一点上使用它。
所以我尝试了:
export interface ResponseParams {
[0]: FirstType;
[1]: SecondType;
...
[n]: NthType;
}
和:
.then((array : ResponseParams) => {
// do things with response
});
但我收到此错误:
类型“ ResponseParams”不是数组类型。
我该如何外化类型并使代码更整洁?
谢谢
您可以使用类型别名定义此类:
type ResponseParams = [FirstType, SecondType, ..., NthType]
但我要指出的是,array
无需显式的类型注释(至少可用于10个Promise)即可推断出的类型:
declare let firstRequest : Promise<{a: number}>
declare let secondRequest : Promise<{b: number}>
declare let nthRequest : Promise<{c: number}>
Promise.all([
firstRequest,
secondRequest,
nthRequest
])
.then((array) => { // array is of type [{a: number;}, {b: number;}, {c: number;}]
// do things with response
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句