跳到主要内容

Awaited

介绍

假如我们有一个 Promise 对象,这个 Promise 对象会返回一个类型。在 TS 中,我们用 Promise<T> 中的 T 来描述这个 Promise 返回的类型。请你实现一个类型,可以获取这个类型。

例如:Promise<ExampleType>,请你返回 ExampleType 类型。

This question is ported from the original article by @maciejsikora

View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
type Awaited<T> = any;
Duplicate identifier 'Awaited'.2300Duplicate identifier 'Awaited'.
 
/* _____________ Test Cases _____________ */
type X = Promise<string>;
type Y = Promise<{ field: number }>;
 
type cases = [
Expect<Equal<Awaited<X>, string>>,
Expect<Equal<Awaited<Y>, { field: number }>>
];
ts
/* _____________ Your Code Here _____________ */
type Awaited<T> = any;
Duplicate identifier 'Awaited'.2300Duplicate identifier 'Awaited'.
 
/* _____________ Test Cases _____________ */
type X = Promise<string>;
type Y = Promise<{ field: number }>;
 
type cases = [
Expect<Equal<Awaited<X>, string>>,
Expect<Equal<Awaited<Y>, { field: number }>>
];
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
// type Awaited<T extends Promise<unknown>> = T extends Promise<infer R> ? R : never;
type Awaited<T extends Promise<unknown>> = T extends Promise<infer R> ? R extends Promise<unknown> ? Awaited<R> : R : never
Duplicate identifier 'Awaited'.2300Duplicate identifier 'Awaited'.
ts
// type Awaited<T extends Promise<unknown>> = T extends Promise<infer R> ? R : never;
type Awaited<T extends Promise<unknown>> = T extends Promise<infer R> ? R extends Promise<unknown> ? Awaited<R> : R : never
Duplicate identifier 'Awaited'.2300Duplicate identifier 'Awaited'.
view more solutions