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

Improve narrowing of generic types constrained to unknown #60816

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 30 additions & 12 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27615,8 +27615,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return mapType(type, t => hasTypeFacts(t, targetFacts) ? getIntersectionType([t, !(facts & otherIncludesFacts) && hasTypeFacts(t, otherFacts) ? emptyAndOtherUnion : emptyObjectType]) : t);
}

function recombineUnknownType(type: Type) {
return type === unknownUnionType ? unknownType : type;
function recombineUnknownType(type: Type, recombinedType: Type = unknownType) {
return type === unknownUnionType ? recombinedType : type;
}

function getTypeWithDefault(type: Type, defaultExpression: Expression) {
Expand Down Expand Up @@ -29793,7 +29793,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
function isGenericTypeWithUnionConstraint(type: Type): boolean {
return type.flags & TypeFlags.Intersection ?
some((type as IntersectionType).types, isGenericTypeWithUnionConstraint) :
!!(type.flags & TypeFlags.Instantiable && getBaseConstraintOrType(type).flags & (TypeFlags.Nullable | TypeFlags.Union));
!!(type.flags & TypeFlags.Instantiable && getBaseConstraintOrType(type).flags & (TypeFlags.Unknown | TypeFlags.Nullable | TypeFlags.Union));
}

function isGenericTypeWithoutNullableConstraint(type: Type): boolean {
Expand Down Expand Up @@ -29829,7 +29829,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const substituteConstraints = !(checkMode && checkMode & CheckMode.Inferential) &&
someType(type, isGenericTypeWithUnionConstraint) &&
(forReturnTypeNarrowing || isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode));
return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type;
return substituteConstraints
? mapType(type, t => {
const c = getBaseConstraintOrType(t);
return c.flags & TypeFlags.Unknown ? unknownUnionType : c;
})
: type;
}

function isExportOrExportExpression(location: Node) {
Expand Down Expand Up @@ -30498,6 +30503,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return type;
}

const originalType = type;
type = getNarrowableTypeForReference(type, node, checkMode);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there are 2 other calls to getNarrowableTypeForReference that are now not accompanied by this recombineUnknownType dance. Before landing this, I should recheck both to see if that's OK.

One of them is in checkReturnExpression - @gabritto do you have an opinion about this? This fix improves this scenario:

// this one doesn't work without this fix
function test1<T extends unknown>(
  x: T,
): T extends {} ? {} : T extends Nullable ? Nullable : never {
  if (x == undefined) {
    return x;
  } else {
    return x;
  }
}

type Nullable = null | undefined;

// this one works
function test2<T extends {} | Nullable>(
  x: T,
): T extends {} ? {} : T extends Nullable ? Nullable : never {
  if (x == undefined) {
    return x;
  } else {
    return x;
  }
}

but since the returned type can't "escape" the return statement, it feels redundant to recombine that unknown type there


// The declaration container is the innermost function that encloses the declaration of the variable
Expand Down Expand Up @@ -30542,8 +30548,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const initialType = isAutomaticTypeInNonNull ? undefinedType :
assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration as VariableLikeDeclaration) : type) :
typeIsAutomatic ? undefinedType : getOptionalType(type);
const flowType = isAutomaticTypeInNonNull ? getNonNullableType(getFlowTypeOfReference(node, type, initialType, flowContainer)) :
getFlowTypeOfReference(node, type, initialType, flowContainer);
const flowType = recombineUnknownType(
isAutomaticTypeInNonNull
? getNonNullableType(getFlowTypeOfReference(node, type, initialType, flowContainer))
: getFlowTypeOfReference(node, type, initialType, flowContainer),
originalType,
);
// A variable is considered uninitialized when it is possible to analyze the entire control flow graph
// from declaration to use, and when the variable's declared type doesn't include undefined but the
// control flow based type does include undefined.
Expand Down Expand Up @@ -34345,6 +34355,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
if (propType === autoType) {
return getFlowTypeOfProperty(node, prop);
}
const originalPropType = propType;
propType = getNarrowableTypeForReference(propType, node, checkMode);
// If strict null checks and strict property initialization checks are enabled, if we have
// a this.xxx property access, if the property is an instance property without an initializer,
Expand All @@ -34370,7 +34381,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
) {
assumeUninitialized = true;
}
const flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
const flowType = recombineUnknownType(
getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType),
originalPropType,
);
if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) {
error(errorNode, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop!)); // TODO: GH#18217
// Return the declared type to reduce follow-on errors
Expand Down Expand Up @@ -45915,8 +45929,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
function getNarrowableTypeParameters(candidates: TypeParameter[]): [TypeParameter, Symbol, Identifier][] {
const narrowableParams: [TypeParameter, Symbol, Identifier][] = [];
for (const typeParam of candidates) {
const constraint = getConstraintOfTypeParameter(typeParam);
if (!constraint || !(constraint.flags & TypeFlags.Union)) continue;
if (!isGenericTypeWithUnionConstraint(typeParam)) continue;
const constraint = getConstraintOfTypeParameter(typeParam)!;
if (typeParam.symbol && typeParam.symbol.declarations && typeParam.symbol.declarations.length === 1) {
const declaration = typeParam.symbol.declarations[0];
const container = isJSDocTemplateTag(declaration.parent) ? getJSDocHost(declaration.parent) : declaration.parent;
Expand Down Expand Up @@ -46034,11 +46048,15 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

// (2)
const constraintType = getConstraintOfTypeParameter(type.checkType as TypeParameter);
if (!constraintType || !(constraintType.flags & TypeFlags.Union)) {
if (!isGenericTypeWithUnionConstraint(type.checkType)) {
return false;
}
let constraintType = getConstraintOfTypeParameter(type.checkType as TypeParameter)!;
constraintType = constraintType.flags & TypeFlags.Unknown ? unknownUnionType : constraintType;
if (!(constraintType.flags & TypeFlags.Union)) {
// the constraint could be a nullable type
return false;
}

// (3)
if (
!everyType(type.extendsType, extendsType =>
Expand Down
33 changes: 33 additions & 0 deletions tests/baselines/reference/dependentReturnType10.symbols
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//// [tests/cases/compiler/dependentReturnType10.ts] ////

=== dependentReturnType10.ts ===
type Nullable = null | undefined;
>Nullable : Symbol(Nullable, Decl(dependentReturnType10.ts, 0, 0))

function test1<T extends unknown>(
>test1 : Symbol(test1, Decl(dependentReturnType10.ts, 0, 33))
>T : Symbol(T, Decl(dependentReturnType10.ts, 2, 15))

x: T,
>x : Symbol(x, Decl(dependentReturnType10.ts, 2, 34))
>T : Symbol(T, Decl(dependentReturnType10.ts, 2, 15))

): T extends {} ? {} : T extends Nullable ? Nullable : never {
>T : Symbol(T, Decl(dependentReturnType10.ts, 2, 15))
>T : Symbol(T, Decl(dependentReturnType10.ts, 2, 15))
>Nullable : Symbol(Nullable, Decl(dependentReturnType10.ts, 0, 0))
>Nullable : Symbol(Nullable, Decl(dependentReturnType10.ts, 0, 0))

if (x == undefined) {
>x : Symbol(x, Decl(dependentReturnType10.ts, 2, 34))
>undefined : Symbol(undefined)

return x;
>x : Symbol(x, Decl(dependentReturnType10.ts, 2, 34))

} else {
return x;
>x : Symbol(x, Decl(dependentReturnType10.ts, 2, 34))
}
}

35 changes: 35 additions & 0 deletions tests/baselines/reference/dependentReturnType10.types
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//// [tests/cases/compiler/dependentReturnType10.ts] ////

=== dependentReturnType10.ts ===
type Nullable = null | undefined;
>Nullable : Nullable
> : ^^^^^^^^

function test1<T extends unknown>(
>test1 : <T extends unknown>(x: T) => T extends {} ? {} : T extends Nullable ? Nullable : never
> : ^ ^^^^^^^^^ ^^ ^^ ^^^^^

x: T,
>x : T
> : ^

): T extends {} ? {} : T extends Nullable ? Nullable : never {
if (x == undefined) {
>x == undefined : boolean
> : ^^^^^^^
>x : T
> : ^
>undefined : undefined
> : ^^^^^^^^^

return x;
>x : null | undefined
> : ^^^^^^^^^^^^^^^^

} else {
return x;
>x : {}
> : ^^
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//// [tests/cases/compiler/dependentReturnType11.ts] ////

=== dependentReturnType11.ts ===
// shouldn't crash

type Nullable = null | undefined;
>Nullable : Symbol(Nullable, Decl(dependentReturnType11.ts, 0, 0))

function test1<T extends null>(
>test1 : Symbol(test1, Decl(dependentReturnType11.ts, 2, 33))
>T : Symbol(T, Decl(dependentReturnType11.ts, 4, 15))

x: T,
>x : Symbol(x, Decl(dependentReturnType11.ts, 4, 31))
>T : Symbol(T, Decl(dependentReturnType11.ts, 4, 15))

): T extends Nullable ? Nullable : never {
>T : Symbol(T, Decl(dependentReturnType11.ts, 4, 15))
>Nullable : Symbol(Nullable, Decl(dependentReturnType11.ts, 0, 0))
>Nullable : Symbol(Nullable, Decl(dependentReturnType11.ts, 0, 0))

if (x == undefined) {
>x : Symbol(x, Decl(dependentReturnType11.ts, 4, 31))
>undefined : Symbol(undefined)

return x;
>x : Symbol(x, Decl(dependentReturnType11.ts, 4, 31))
}
return x;
>x : Symbol(x, Decl(dependentReturnType11.ts, 4, 31))
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//// [tests/cases/compiler/dependentReturnType11.ts] ////

=== dependentReturnType11.ts ===
// shouldn't crash

type Nullable = null | undefined;
>Nullable : null
> : ^^^^

function test1<T extends null>(
>test1 : <T extends null>(x: T) => T extends Nullable ? Nullable : never
> : ^ ^^^^^^^^^ ^^ ^^ ^^^^^

x: T,
>x : T
> : ^

): T extends Nullable ? Nullable : never {
if (x == undefined) {
>x == undefined : boolean
> : ^^^^^^^
>x : T
> : ^
>undefined : undefined
> : ^^^^^^^^^

return x;
>x : T
> : ^
}
return x;
>x : T
> : ^
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
dependentReturnType11.ts(9,5): error TS2322: Type 'T' is not assignable to type 'T extends Nullable ? Nullable : never'.
Type 'null' is not assignable to type 'T extends Nullable ? Nullable : never'.


==== dependentReturnType11.ts (1 errors) ====
// shouldn't crash

type Nullable = null | undefined;

function test1<T extends null>(
x: T,
): T extends Nullable ? Nullable : never {
if (x == undefined) {
return x;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in theory, this shouldn't report an error but this code is just awfully non-sensical, I only have added it as extra precautions against potential crashes (that didn't happen - but somewhat only because some helper is OK with undefined argument)

~~~~~~
!!! error TS2322: Type 'T' is not assignable to type 'T extends Nullable ? Nullable : never'.
!!! error TS2322: Type 'null' is not assignable to type 'T extends Nullable ? Nullable : never'.
}
return x;
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//// [tests/cases/compiler/dependentReturnType11.ts] ////

=== dependentReturnType11.ts ===
// shouldn't crash

type Nullable = null | undefined;
>Nullable : Symbol(Nullable, Decl(dependentReturnType11.ts, 0, 0))

function test1<T extends null>(
>test1 : Symbol(test1, Decl(dependentReturnType11.ts, 2, 33))
>T : Symbol(T, Decl(dependentReturnType11.ts, 4, 15))

x: T,
>x : Symbol(x, Decl(dependentReturnType11.ts, 4, 31))
>T : Symbol(T, Decl(dependentReturnType11.ts, 4, 15))

): T extends Nullable ? Nullable : never {
>T : Symbol(T, Decl(dependentReturnType11.ts, 4, 15))
>Nullable : Symbol(Nullable, Decl(dependentReturnType11.ts, 0, 0))
>Nullable : Symbol(Nullable, Decl(dependentReturnType11.ts, 0, 0))

if (x == undefined) {
>x : Symbol(x, Decl(dependentReturnType11.ts, 4, 31))
>undefined : Symbol(undefined)

return x;
>x : Symbol(x, Decl(dependentReturnType11.ts, 4, 31))
}
return x;
>x : Symbol(x, Decl(dependentReturnType11.ts, 4, 31))
}

35 changes: 35 additions & 0 deletions tests/baselines/reference/dependentReturnType11(strict=true).types
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//// [tests/cases/compiler/dependentReturnType11.ts] ////

=== dependentReturnType11.ts ===
// shouldn't crash

type Nullable = null | undefined;
>Nullable : Nullable
> : ^^^^^^^^

function test1<T extends null>(
>test1 : <T extends null>(x: T) => T extends Nullable ? Nullable : never
> : ^ ^^^^^^^^^ ^^ ^^ ^^^^^

x: T,
>x : T
> : ^

): T extends Nullable ? Nullable : never {
if (x == undefined) {
>x == undefined : boolean
> : ^^^^^^^
>x : T
> : ^
>undefined : undefined
> : ^^^^^^^^^

return x;
>x : T
> : ^
}
return x;
>x : never
> : ^^^^^
}

Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ genericConditionalConstrainedToUnknownNotAssignableToConcreteObject.ts(13,5): er
M extends keyof T
>(a2: ReturnType<T[M]>) {
if (isA(a2)) {
// a2 is not narrowed
a2.x // error, but should be ok
Comment on lines -42 to -43
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

those were outdated comments, as we can see here - no errors are reported here (rightfully so). I took the liberty to fix those here

a2.x // ok
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ function g2<
M extends keyof T
>(a2: ReturnType<T[M]>) {
if (isA(a2)) {
// a2 is not narrowed
a2.x // error, but should be ok
a2.x // ok
}
}

Expand All @@ -36,7 +35,6 @@ function g(a2, x) {
// Original CFA report of the above issue
function g2(a2) {
if (isA(a2)) {
// a2 is not narrowed
a2.x; // error, but should be ok
a2.x; // ok
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ function g2<
>isA : Symbol(isA, Decl(genericConditionalConstrainedToUnknownNotAssignableToConcreteObject.ts, 0, 25))
>a2 : Symbol(a2, Decl(genericConditionalConstrainedToUnknownNotAssignableToConcreteObject.ts, 20, 2))

// a2 is not narrowed
a2.x // error, but should be ok
a2.x // ok
>a2.x : Symbol(A.x, Decl(genericConditionalConstrainedToUnknownNotAssignableToConcreteObject.ts, 0, 13))
>a2 : Symbol(a2, Decl(genericConditionalConstrainedToUnknownNotAssignableToConcreteObject.ts, 20, 2))
>x : Symbol(A.x, Decl(genericConditionalConstrainedToUnknownNotAssignableToConcreteObject.ts, 0, 13))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,11 @@ function g2<
>a2 : ReturnType<T[M]>
> : ^^^^^^^^^^^^^^^^

// a2 is not narrowed
a2.x // error, but should be ok
a2.x // ok
>a2.x : number
> : ^^^^^^
>a2 : ReturnType<T[M]> & A
> : ^^^^^^^^^^^^^^^^^^^^
>a2 : A
> : ^
>x : number
> : ^^^^^^
}
Expand Down
Loading
Loading