Awaited
介绍
假如我们有一个 Promise 对象,这个 Promise 对象会返回一个类型。在 TS 中,我们用 Promise<T>
中的 T 来描述这个 Promise 返回的类型。请你实现一个类型,可以获取这个类型。
例如:Promise<ExampleType>
,请你返回 ExampleType 类型。
View on GitHubThis question is ported from the original article by @maciejsikora
起点
ts
/* _____________ Your Code Here _____________ */typeDuplicate identifier 'Awaited'.2300Duplicate identifier 'Awaited'.< Awaited T > = any;/* _____________ Test Cases _____________ */typeX =Promise <string>;typeY =Promise <{field : number }>;typecases = [Expect <Equal <Awaited <X >, string>>,Expect <Equal <Awaited <Y >, {field : number }>>];
take the challengets
/* _____________ Your Code Here _____________ */typeDuplicate identifier 'Awaited'.2300Duplicate identifier 'Awaited'.< Awaited T > = any;/* _____________ Test Cases _____________ */typeX =Promise <string>;typeY =Promise <{field : number }>;typecases = [Expect <Equal <Awaited <X >, string>>,Expect <Equal <Awaited <Y >, {field : number }>>];
解决方案
Spoiler warning // Click to reveal answer
ts
// type Awaited<T extends Promise<unknown>> = T extends Promise<infer R> ? R : never;typeDuplicate identifier 'Awaited'.2300Duplicate identifier 'Awaited'.< Awaited T extendsPromise <unknown>> =T extendsPromise <inferR > ?R extendsPromise <unknown> ?Awaited <R > :R : never
ts
// type Awaited<T extends Promise<unknown>> = T extends Promise<infer R> ? R : never;typeDuplicate identifier 'Awaited'.2300Duplicate identifier 'Awaited'.< Awaited T extendsPromise <unknown>> =T extendsPromise <inferR > ?R extendsPromise <unknown> ?Awaited <R > :R : never