【问题标题】:Promise.all wrapper with tuple type元组类型的 Promise.all 包装器
【发布时间】:2019-01-27 12:27:58
【问题描述】:

我想使用元组类型为 promise.all 创建一个包装器。我正要写这样的东西:

export function parallerRequest<TResponses extends any[]>(urls: string[]): Promise<TResponses> {
    return Promise.all<TResponses>(urls.map((url) => fetch(url)));
}

预期的行为应该是当 Promise.all 将被解析时,返回的数据将采用提供的元组的形式。任何想法如何实现这种行为?

【问题讨论】:

  • 什么不起作用?你得到了什么错误?
  • 类型“响应”不可分配给类型“TResponses”。

标签: typescript typescript3.0


【解决方案1】:

即使Promise.all() 对元组类型进行了适当的映射(至少在 TypeScript 3.1 发布之前不会是 supported),问题是编译器无法验证映射的结果fetch 超过 urls 将产生 TResponses 类型的值。它只知道它将是Response[] 类型,它比TResponses 宽。因此Promise.all 返回一个Promise&lt;Response[]&gt;。如果您想告诉编译器不要担心,可以使用type assertion

export function parallelRequest<TResponses extends Response[]>(
  urls: string[]
): Promise<TResponses> {
    return Promise.all(urls.map(x => fetch(x))) as Promise<TResponses>; // okay
}

这行得通。但请注意,编译器警告是一个很好的警告。 parallelRequest() 的签名中没有任何内容可以保证,例如,urls 的长度与 TResponses 的长度相同,或者有人不会为 TResponses 的元素传递 Response 的子类型:

interface CustomResponse extends Response {
    prop: string;
}
parallelRequest<[Response, CustomResponse, Response]>(["/foo/bar", "/baz"]); // no error

所以这并不是真正的类型安全。我不确定您指定TResponses 的用例是什么,而不是只留下Response[],但您应该小心。

无论如何希望这会有所帮助。祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多