Skip to content

Commit f1d5bc2

Browse files
committed
Defer generic awaited type
1 parent 70b902e commit f1d5bc2

27 files changed

+295
-723
lines changed

src/compiler/checker.ts

Lines changed: 15 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,7 @@ namespace ts {
800800
let deferredGlobalESSymbolConstructorSymbol: Symbol | undefined;
801801
let deferredGlobalESSymbolType: ObjectType;
802802
let deferredGlobalTypedPropertyDescriptorType: GenericType;
803+
let deferredGlobalAwaitedSymbol: Symbol | undefined;
803804
let deferredGlobalPromiseType: GenericType;
804805
let deferredGlobalPromiseLikeType: GenericType;
805806
let deferredGlobalPromiseConstructorSymbol: Symbol | undefined;
@@ -853,7 +854,6 @@ namespace ts {
853854
const flowNodeReachable: (boolean | undefined)[] = [];
854855
const potentialThisCollisions: Node[] = [];
855856
const potentialNewTargetCollisions: Node[] = [];
856-
const awaitedTypeStack: number[] = [];
857857

858858
const diagnostics = createDiagnosticCollection();
859859
const suggestionDiagnostics = createDiagnosticCollection();
@@ -11070,6 +11070,10 @@ namespace ts {
1107011070
return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol" as __String, /*arity*/ 0, reportErrors)) || emptyObjectType;
1107111071
}
1107211072

11073+
function getGlobalAwaitedSymbol(reportErrors: boolean) {
11074+
return deferredGlobalAwaitedSymbol || (deferredGlobalAwaitedSymbol = getGlobalTypeSymbol("Awaited" as __String, reportErrors));
11075+
}
11076+
1107311077
function getGlobalPromiseType(reportErrors: boolean) {
1107411078
return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise" as __String, /*arity*/ 1, reportErrors)) || emptyGenericType;
1107511079
}
@@ -29013,98 +29017,22 @@ namespace ts {
2901329017
return typeAsAwaitable.awaitedTypeOfType = type;
2901429018
}
2901529019

29016-
if (type.flags & TypeFlags.Union) {
29017-
let types: Type[] | undefined;
29018-
for (const constituentType of (<UnionType>type).types) {
29019-
types = append<Type>(types, getAwaitedType(constituentType, errorNode, diagnosticMessage, arg0));
29020-
}
29021-
29022-
if (!types) {
29023-
return undefined;
29024-
}
29025-
29026-
return typeAsAwaitable.awaitedTypeOfType = getUnionType(types);
29020+
const symbol = getGlobalAwaitedSymbol(/*reportErrors*/ false);
29021+
if (!symbol) {
29022+
return typeAsAwaitable.awaitedTypeOfType = type;
2902729023
}
2902829024

29029-
const promisedType = getPromisedTypeOfPromise(type);
29030-
if (promisedType) {
29031-
if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) {
29032-
// Verify that we don't have a bad actor in the form of a promise whose
29033-
// promised type is the same as the promise type, or a mutually recursive
29034-
// promise. If so, we return undefined as we cannot guess the shape. If this
29035-
// were the actual case in the JavaScript, this Promise would never resolve.
29036-
//
29037-
// An example of a bad actor with a singly-recursive promise type might
29038-
// be:
29039-
//
29040-
// interface BadPromise {
29041-
// then(
29042-
// onfulfilled: (value: BadPromise) => any,
29043-
// onrejected: (error: any) => any): BadPromise;
29044-
// }
29045-
// The above interface will pass the PromiseLike check, and return a
29046-
// promised type of `BadPromise`. Since this is a self reference, we
29047-
// don't want to keep recursing ad infinitum.
29048-
//
29049-
// An example of a bad actor in the form of a mutually-recursive
29050-
// promise type might be:
29051-
//
29052-
// interface BadPromiseA {
29053-
// then(
29054-
// onfulfilled: (value: BadPromiseB) => any,
29055-
// onrejected: (error: any) => any): BadPromiseB;
29056-
// }
29057-
//
29058-
// interface BadPromiseB {
29059-
// then(
29060-
// onfulfilled: (value: BadPromiseA) => any,
29061-
// onrejected: (error: any) => any): BadPromiseA;
29062-
// }
29063-
//
29064-
if (errorNode) {
29065-
error(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
29066-
}
29067-
return undefined;
29068-
}
29069-
29070-
// Keep track of the type we're about to unwrap to avoid bad recursive promise types.
29071-
// See the comments above for more information.
29072-
awaitedTypeStack.push(type.id);
29073-
const awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
29074-
awaitedTypeStack.pop();
29075-
29076-
if (!awaitedType) {
29077-
return undefined;
29078-
}
29079-
29080-
return typeAsAwaitable.awaitedTypeOfType = awaitedType;
29025+
const result = getTypeAliasInstantiation(symbol, [type]);
29026+
if (result !== unknownType || type === unknownType || getPromisedTypeOfPromise(type) === unknownType) {
29027+
return typeAsAwaitable.awaitedTypeOfType = (result as PromiseOrAwaitableType).awaitedTypeOfType = result;
2908129028
}
2908229029

29083-
// The type was not a promise, so it could not be unwrapped any further.
29084-
// As long as the type does not have a callable "then" property, it is
29085-
// safe to return the type; otherwise, an error will be reported in
29086-
// the call to getNonThenableType and we will return undefined.
29087-
//
29088-
// An example of a non-promise "thenable" might be:
29089-
//
29090-
// await { then(): void {} }
29091-
//
29092-
// The "thenable" does not match the minimal definition for a promise. When
29093-
// a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
29094-
// will never settle. We treat this as an error to help flag an early indicator
29095-
// of a runtime problem. If the user wants to return this value from an async
29096-
// function, they would need to wrap it in some other value. If they want it to
29097-
// be treated as a promise, they can cast to <any>.
29098-
const thenFunction = getTypeOfPropertyOfType(type, "then" as __String);
29099-
if (thenFunction && getSignaturesOfType(thenFunction, SignatureKind.Call).length > 0) {
29100-
if (errorNode) {
29101-
if (!diagnosticMessage) return Debug.fail();
29102-
error(errorNode, diagnosticMessage, arg0);
29103-
}
29104-
return undefined;
29030+
if (errorNode) {
29031+
if (!diagnosticMessage) return Debug.fail();
29032+
error(errorNode, diagnosticMessage, arg0);
2910529033
}
2910629034

29107-
return typeAsAwaitable.awaitedTypeOfType = type;
29035+
return undefined;
2910829036
}
2910929037

2911029038
/**

src/harness/fourslashInterface.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -944,6 +944,7 @@ namespace FourSlashInterface {
944944
typeEntry("PropertyDecorator"),
945945
typeEntry("MethodDecorator"),
946946
typeEntry("ParameterDecorator"),
947+
typeEntry("Awaited"),
947948
typeEntry("PromiseConstructorLike"),
948949
interfaceEntry("PromiseLike"),
949950
interfaceEntry("Promise"),
@@ -1602,4 +1603,4 @@ namespace FourSlashInterface {
16021603
readonly providePrefixAndSuffixTextForRename?: boolean;
16031604
};
16041605
export type RenameLocationOptions = FourSlash.Range | { readonly range: FourSlash.Range, readonly prefixText?: string, readonly suffixText?: string };
1605-
}
1606+
}

src/lib/es5.d.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1378,6 +1378,11 @@ declare type PropertyDecorator = (target: Object, propertyKey: string | symbol)
13781378
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
13791379
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
13801380

1381+
// The undefined case is for strictNullChecks false, in which case
1382+
// undefined extends PromiseLike<infer U> is true, which would otherwise
1383+
// make Awaited<undefined> -> unknown.
1384+
type Awaited<T> = T extends undefined ? T : T extends PromiseLike<infer U> ? U : T extends { then(...args: any[]): any } ? unknown : T;
1385+
13811386
declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>;
13821387

13831388
interface PromiseLike<T> {

tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.types

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ class C {
66
>method : () => void
77

88
var fn = async () => await this;
9-
>fn : () => Promise<this>
10-
>async () => await this : () => Promise<this>
11-
>await this : this
9+
>fn : () => Promise<Awaited<this>>
10+
>async () => await this : () => Promise<Awaited<this>>
11+
>await this : Awaited<this>
1212
>this : this
1313
}
1414
}

tests/baselines/reference/asyncArrowFunctionCapturesThis_es5.types

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ class C {
66
>method : () => void
77

88
var fn = async () => await this;
9-
>fn : () => Promise<this>
10-
>async () => await this : () => Promise<this>
11-
>await this : this
9+
>fn : () => Promise<Awaited<this>>
10+
>async () => await this : () => Promise<Awaited<this>>
11+
>await this : Awaited<this>
1212
>this : this
1313
}
1414
}

tests/baselines/reference/asyncArrowFunctionCapturesThis_es6.types

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ class C {
66
>method : () => void
77

88
var fn = async () => await this;
9-
>fn : () => Promise<this>
10-
>async () => await this : () => Promise<this>
11-
>await this : this
9+
>fn : () => Promise<Awaited<this>>
10+
>async () => await this : () => Promise<Awaited<this>>
11+
>await this : Awaited<this>
1212
>this : this
1313
}
1414
}

tests/baselines/reference/asyncFunctionReturnType.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ async function fGenericIndexedTypeForExplicitPromiseOfAnyProp<TObj extends Obj>(
6363
return Promise.resolve<TObj["anyProp"]>(obj.anyProp);
6464
}
6565

66-
async function fGenericIndexedTypeForKProp<TObj extends Obj, K extends keyof TObj>(obj: TObj, key: K): Promise<TObj[K]> {
66+
async function fGenericIndexedTypeForKProp<TObj extends Obj, K extends keyof TObj>(obj: TObj, key: K): Promise<Awaited<TObj[K]>> {
6767
return obj[key];
6868
}
6969

@@ -73,7 +73,8 @@ async function fGenericIndexedTypeForPromiseOfKProp<TObj extends Obj, K extends
7373

7474
async function fGenericIndexedTypeForExplicitPromiseOfKProp<TObj extends Obj, K extends keyof TObj>(obj: TObj, key: K): Promise<TObj[K]> {
7575
return Promise.resolve<TObj[K]>(obj[key]);
76-
}
76+
}
77+
7778

7879
//// [asyncFunctionReturnType.js]
7980
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

tests/baselines/reference/asyncFunctionReturnType.symbols

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ async function fGenericIndexedTypeForExplicitPromiseOfAnyProp<TObj extends Obj>(
221221
>anyProp : Symbol(Obj.anyProp, Decl(asyncFunctionReturnType.ts, 12, 23))
222222
}
223223

224-
async function fGenericIndexedTypeForKProp<TObj extends Obj, K extends keyof TObj>(obj: TObj, key: K): Promise<TObj[K]> {
224+
async function fGenericIndexedTypeForKProp<TObj extends Obj, K extends keyof TObj>(obj: TObj, key: K): Promise<Awaited<TObj[K]>> {
225225
>fGenericIndexedTypeForKProp : Symbol(fGenericIndexedTypeForKProp, Decl(asyncFunctionReturnType.ts, 62, 1))
226226
>TObj : Symbol(TObj, Decl(asyncFunctionReturnType.ts, 64, 43))
227227
>Obj : Symbol(Obj, Decl(asyncFunctionReturnType.ts, 8, 1))
@@ -232,6 +232,7 @@ async function fGenericIndexedTypeForKProp<TObj extends Obj, K extends keyof TOb
232232
>key : Symbol(key, Decl(asyncFunctionReturnType.ts, 64, 93))
233233
>K : Symbol(K, Decl(asyncFunctionReturnType.ts, 64, 60))
234234
>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
235+
>Awaited : Symbol(Awaited, Decl(lib.es5.d.ts, --, --))
235236
>TObj : Symbol(TObj, Decl(asyncFunctionReturnType.ts, 64, 43))
236237
>K : Symbol(K, Decl(asyncFunctionReturnType.ts, 64, 60))
237238

@@ -285,3 +286,4 @@ async function fGenericIndexedTypeForExplicitPromiseOfKProp<TObj extends Obj, K
285286
>obj : Symbol(obj, Decl(asyncFunctionReturnType.ts, 72, 100))
286287
>key : Symbol(key, Decl(asyncFunctionReturnType.ts, 72, 110))
287288
}
289+

tests/baselines/reference/asyncFunctionReturnType.types

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,8 +180,8 @@ async function fGenericIndexedTypeForExplicitPromiseOfAnyProp<TObj extends Obj>(
180180
>anyProp : any
181181
}
182182

183-
async function fGenericIndexedTypeForKProp<TObj extends Obj, K extends keyof TObj>(obj: TObj, key: K): Promise<TObj[K]> {
184-
>fGenericIndexedTypeForKProp : <TObj extends Obj, K extends keyof TObj>(obj: TObj, key: K) => Promise<TObj[K]>
183+
async function fGenericIndexedTypeForKProp<TObj extends Obj, K extends keyof TObj>(obj: TObj, key: K): Promise<Awaited<TObj[K]>> {
184+
>fGenericIndexedTypeForKProp : <TObj extends Obj, K extends keyof TObj>(obj: TObj, key: K) => Promise<Awaited<TObj[K]>>
185185
>obj : TObj
186186
>key : K
187187

@@ -220,3 +220,4 @@ async function fGenericIndexedTypeForExplicitPromiseOfKProp<TObj extends Obj, K
220220
>obj : TObj
221221
>key : K
222222
}
223+

tests/baselines/reference/compareTypeParameterConstrainedByLiteralToLiteral.errors.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,6 @@ tests/cases/compiler/compareTypeParameterConstrainedByLiteralToLiteral.ts(5,5):
99
t === "x"; // Should be error
1010
~~~~~~~~~
1111
!!! error TS2367: This condition will always return 'false' since the types 'T' and '"x"' have no overlap.
12+
!!! related TS2773 tests/cases/compiler/compareTypeParameterConstrainedByLiteralToLiteral.ts:5:5: Did you forget to use 'await'?
1213
}
1314

0 commit comments

Comments
 (0)