需求是这样的,有一个 test 函数
最终想要达到的效果:
// 伪代码
function test(data) {}
const [r1,r2] = await test([ () => Promise.resolve(1), () => Promise.resolve(true) ])
// 类型:[number, boolean]
我参考了 Promise.all 的类型定义,
Promise.all 的类型定义:
all<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }>;
弄出下面的类型定义:
function test<T extends readonly (() => Promise<any>)[]>(data: T): Promise<{
-readonly [p in keyof T]: Awaited<
T[p] extends () => Promise<any> ? ReturnType<T[p]> : T[p]
>
}> {}
但出来的效果是这样的:
const [r1,r2] = await test([ () => Promise.resolve(1), () => Promise.resolve(true) ])
// 类型:[number | boolean, number | boolean]
每个值的类型推断都是 | ,而 Promise.all 能精确地指出数组每个值分别是什么类型
所以我想请教下大家,如何修改上面的定义,让 TypeScript 推断的类型从
[number | boolean, number | boolean]
变为 [number, boolean]
1
hsfzxjy 2022-04-16 10:59:20 +08:00 via Android 1
|
2
noe132 2022-04-16 11:22:55 +08:00 1
() => Promise<any>[] 是一个 Array Type
你需要把它转换成 Tuple Type 。可以像 Promise.all 改成 T extends readonly (() => Promise<any>)[] | [] 也可以在参数类型改成 data: [...T] 参考 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#variadic-tuple-types https://github.com/type-challenges/type-challenges/issues/3444 https://github.com/type-challenges/type-challenges/issues/1924 https://www.typescriptlang.org/play?target=99#code/CYUwxgNghgTiAEYD2A7AzgF3jArigKlGgNZoBc8APPvCAB4YgrBrYhTCoQCe8AFHwCU8ALwA+eAAUYSALYBLNCEp5iKJAHcUYwQG0AumL4A3KBBwhy8fMPFSZCpZQDeAKHjxdAaXjyU8YhBuJAAza30KH3pGZlYUHFkAIxAYdw94AH57OUUQAGUQDAwIEGAAJUscCAxKAEENKHlGYEoKjBwYAm4AB2V8b0MxMTSPClV1LVcAX2HXZHQsWUb-EXgibhQwflsJN3TEVEw2NCqsVagGpuw8QhI0Pl0R-e3RCWkcpQA6ODQkCGMQHwAIyCAA0T32Qle2UcIG+lj+AL4AHIAEzIsEQ9JQuzvWHw37-QEhMxKTH7fSCaauIA |
3
noe132 2022-04-16 11:25:14 +08:00
|