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 1 commit
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
28 changes: 21 additions & 7 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
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
59 changes: 59 additions & 0 deletions tests/baselines/reference/narrowUnknownByTypePredicate.errors.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
narrowUnknownByTypePredicate.ts(41,11): error TS2322: Type 'T' is not assignable to type 'null | undefined'.


==== narrowUnknownByTypePredicate.ts (1 errors) ====
declare function isNotNullish(value: unknown): value is {};
declare function isNullish(value: unknown): value is null | undefined;

declare const value1: unknown;
if (isNotNullish(value1)) {
value1;
}

declare const value2: unknown;
if (!isNotNullish(value2)) {
value2;
}

declare const value3: unknown;
if (isNullish(value3)) {
value3;
}

declare const value4: unknown;
if (!isNullish(value4)) {
value4;
}

declare class A { foo: string; }
declare function isA(value: unknown): value is A;

declare const value5: unknown;
if (isA(value5)) {
value5;
}

declare const value6: unknown;
if (!isA(value6)) {
value6;
}

function fn1<T>(x: T): void {
if (x != undefined) {
const y: {} = x; // ok
} else {
const y: null | undefined = x; // ok
~
!!! error TS2322: Type 'T' is not assignable to type 'null | undefined'.
!!! related TS2208 narrowUnknownByTypePredicate.ts:37:14: This type parameter might need an `extends null | undefined` constraint.
Comment on lines +45 to +48
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This one really shouldn't error and it should 100% behave like the other case added here. I could work on this further - but like, the simplest potential fix would be to... return unknownType from getBaseConstraintOfType when constraint === noConstraintType. I'll try to do that but I expect that there might be some reason why that isn't unified already like this despite the fact that constraint of an unconstrained type parameter is unknown (in TS files)

}
}

function fn2<T extends unknown>(x: T): void {
if (x != undefined) {
const y: {} = x; // ok
} else {
const y: null | undefined = x; // ok
}
}

42 changes: 42 additions & 0 deletions tests/baselines/reference/narrowUnknownByTypePredicate.symbols
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,45 @@ if (!isA(value6)) {
>value6 : Symbol(value6, Decl(narrowUnknownByTypePredicate.ts, 31, 13))
}

function fn1<T>(x: T): void {
>fn1 : Symbol(fn1, Decl(narrowUnknownByTypePredicate.ts, 34, 1))
>T : Symbol(T, Decl(narrowUnknownByTypePredicate.ts, 36, 13))
>x : Symbol(x, Decl(narrowUnknownByTypePredicate.ts, 36, 16))
>T : Symbol(T, Decl(narrowUnknownByTypePredicate.ts, 36, 13))

if (x != undefined) {
>x : Symbol(x, Decl(narrowUnknownByTypePredicate.ts, 36, 16))
>undefined : Symbol(undefined)

const y: {} = x; // ok
>y : Symbol(y, Decl(narrowUnknownByTypePredicate.ts, 38, 9))
>x : Symbol(x, Decl(narrowUnknownByTypePredicate.ts, 36, 16))

} else {
const y: null | undefined = x; // ok
>y : Symbol(y, Decl(narrowUnknownByTypePredicate.ts, 40, 9))
>x : Symbol(x, Decl(narrowUnknownByTypePredicate.ts, 36, 16))
}
}

function fn2<T extends unknown>(x: T): void {
>fn2 : Symbol(fn2, Decl(narrowUnknownByTypePredicate.ts, 42, 1))
>T : Symbol(T, Decl(narrowUnknownByTypePredicate.ts, 44, 13))
>x : Symbol(x, Decl(narrowUnknownByTypePredicate.ts, 44, 32))
>T : Symbol(T, Decl(narrowUnknownByTypePredicate.ts, 44, 13))

if (x != undefined) {
>x : Symbol(x, Decl(narrowUnknownByTypePredicate.ts, 44, 32))
>undefined : Symbol(undefined)

const y: {} = x; // ok
>y : Symbol(y, Decl(narrowUnknownByTypePredicate.ts, 46, 9))
>x : Symbol(x, Decl(narrowUnknownByTypePredicate.ts, 44, 32))

} else {
const y: null | undefined = x; // ok
>y : Symbol(y, Decl(narrowUnknownByTypePredicate.ts, 48, 9))
>x : Symbol(x, Decl(narrowUnknownByTypePredicate.ts, 44, 32))
}
}

58 changes: 58 additions & 0 deletions tests/baselines/reference/narrowUnknownByTypePredicate.types
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,61 @@ if (!isA(value6)) {
> : ^^^^^^^
}

function fn1<T>(x: T): void {
>fn1 : <T>(x: T) => void
> : ^ ^^ ^^ ^^^^^
>x : T
> : ^

if (x != undefined) {
>x != undefined : boolean
> : ^^^^^^^
>x : T
> : ^
>undefined : undefined
> : ^^^^^^^^^

const y: {} = x; // ok
>y : {}
> : ^^
>x : NonNullable<T>
> : ^^^^^^^^^^^^^^

} else {
const y: null | undefined = x; // ok
>y : null | undefined
> : ^^^^^^^^^^^^^^^^
>x : T
> : ^
}
}

function fn2<T extends unknown>(x: T): void {
>fn2 : <T extends unknown>(x: T) => void
> : ^ ^^^^^^^^^ ^^ ^^ ^^^^^
>x : T
> : ^

if (x != undefined) {
>x != undefined : boolean
> : ^^^^^^^
>x : T
> : ^
>undefined : undefined
> : ^^^^^^^^^

const y: {} = x; // ok
>y : {}
> : ^^
>x : {}
> : ^^

} else {
const y: null | undefined = x; // ok
>y : null | undefined
> : ^^^^^^^^^^^^^^^^
>x : null | undefined
> : ^^^^^^^^^^^^^^^^
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ 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
}
}
16 changes: 16 additions & 0 deletions tests/cases/compiler/narrowUnknownByTypePredicate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,19 @@ declare const value6: unknown;
if (!isA(value6)) {
value6;
}

function fn1<T>(x: T): void {
if (x != undefined) {
const y: {} = x; // ok
} else {
const y: null | undefined = x; // ok
}
}

function fn2<T extends unknown>(x: T): void {
if (x != undefined) {
const y: {} = x; // ok
} else {
const y: null | undefined = x; // ok
}
}
Loading