Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

23. PromiseAll #32

Open
astak16 opened this issue Jun 25, 2022 · 0 comments
Open

23. PromiseAll #32

astak16 opened this issue Jun 25, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Jun 25, 2022

题目

题目链接:PromiseAll

实现 PromiseAll,满足下面功能

import type { Equal, Expect } from '@type-challenges/utils'

const promiseAllTest1 = PromiseAll([1, 2, 3] as const)
const promiseAllTest2 = PromiseAll([1, 2, Promise.resolve(3)] as const)
const promiseAllTest3 = PromiseAll([1, 2, Promise.resolve(3)])

type cases = [
  Expect<Equal<typeof promiseAllTest1, Promise<[1, 2, 3]>>>,
  Expect<Equal<typeof promiseAllTest2, Promise<[1, 2, number]>>>,
  Expect<Equal<typeof promiseAllTest3, Promise<[number, number, number]>>>,
]

答案

方法一

type TUtil1<T> = T extends Promise<infer R> ? R : T;
type TUtil2<T extends unknown[]> = T extends [infer F, ...infer R]
  ? [TUtil1<F>, ...TUtil2<R>]
  : [];
declare function PromiseAll<T extends unknown[]>(
  values: readonly [...T]
): Promise<TUtil2<T>>;

方法二

declare function PromiseAll<T extends unknown[]>(
  values: readonly [...T]
): Promise<{ [K in keyof T]: T[K] extends Promise<infer R> ? R : T[K] }>;

解析

遍历的方法有两种:

  • 递归(方法一)
  • 使用 in 变量(方法二)

方法一使用了可变元组类型:(Variadic tuple types)[https://github.com/microsoft/TypeScript/pull/39094]

@astak16 astak16 added the medium label Jun 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant