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

Simplify relationship check for conditional type on target side #46429

Merged
merged 5 commits into from
Oct 22, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
41 changes: 7 additions & 34 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15315,13 +15315,6 @@ namespace ts {
return type[cache] = type;
}

function isConditionalTypeAlwaysTrueDisregardingInferTypes(type: ConditionalType) {
const extendsInferParamMapper = type.root.inferTypeParameters && createTypeMapper(type.root.inferTypeParameters, map(type.root.inferTypeParameters, () => wildcardType));
const checkType = type.checkType;
const extendsType = type.extendsType;
return isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(instantiateType(extendsType, extendsInferParamMapper)));
}

function getSimplifiedConditionalType(type: ConditionalType, writing: boolean) {
const checkType = type.checkType;
const extendsType = type.extendsType;
Expand Down Expand Up @@ -19030,35 +19023,15 @@ namespace ts {
resetErrorInfo(saveErrorInfo);
return Ternary.Maybe;
}
const c = target as ConditionalType;
// Check if the conditional is always true or always false but still deferred for distribution purposes
const skipTrue = !isTypeAssignableTo(getPermissiveInstantiation(c.checkType), getPermissiveInstantiation(c.extendsType));
const skipFalse = !skipTrue && isConditionalTypeAlwaysTrueDisregardingInferTypes(c);

// Instantiate with a replacement mapper if the conditional is distributive, replacing the check type with a clone of itself,
// this way {x: string | number, y: string | number} -> (T extends T ? { x: T, y: T } : never) appropriately _fails_ when
// T = string | number (since that will end up distributing and producing `{x: string, y: string} | {x: number, y: number}`,
// to which `{x: string | number, y: string | number}` isn't assignable)
let distributionMapper: TypeMapper | undefined;
const checkVar = getActualTypeVariable(c.root.checkType);
if (c.root.isDistributive && checkVar.flags & TypeFlags.TypeParameter) {
const newParam = cloneTypeParameter(checkVar);
distributionMapper = prependTypeMapping(checkVar, newParam, c.mapper);
newParam.mapper = distributionMapper;
}

// TODO: Find a nice way to include potential conditional type breakdowns in error output, if they seem good (they usually don't)
const expanding = isDeeplyNestedType(target, targetStack, targetDepth);
let localResult: Ternary | undefined = expanding ? Ternary.Maybe : undefined;
if (skipTrue || expanding || (localResult = isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.trueType), distributionMapper) : getTrueTypeFromConditionalType(c), RecursionFlags.Target, /*reportErrors*/ false))) {
if (!skipFalse && !expanding) {
localResult = (localResult || Ternary.Maybe) & isRelatedTo(source, distributionMapper ? instantiateType(getTypeFromTypeNode(c.root.node.falseType), distributionMapper) : getFalseTypeFromConditionalType(c), RecursionFlags.Target, /*reportErrors*/ false);
if (!(target as ConditionalType).root.inferTypeParameters) {
Copy link
Member

Choose a reason for hiding this comment

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

Something @weswigham mentioned in the design meeting is that this also has to gate out distributive conditionals.

Suggested change
if (!(target as ConditionalType).root.inferTypeParameters) {
if (!(target as ConditionalType).root.inferTypeParameters && !(target as ConditionalType).root.isDistributive) {

It would be good to have a test case here if nothing else fails.

Copy link
Member

Choose a reason for hiding this comment

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

Specifically, this is because let's say you're relating {x: U, y: U} where U extends T to a T extends Whatever ? { x: T, y: T } : { x: unknown, y: unknown }, you have to return false because the conditional is going to distribute over T - so let's say T = string | number and U = "a" | 0, that's {x: "a" | 0, y: "a" | 0} related to {x: string, y: string} | {x: number, y: number}, which is clearly false.

Copy link
Member

Choose a reason for hiding this comment

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

(And this kind of relation is precisely what happens during variance analysis of something like T extends Whatever ? { x: T, y: T } : { x: unknown, y: unknown }, so we can't afford to get it wrong, otherwise we'll taint the variance-based non-generic results with incorrect results)

if (result = isRelatedTo(source, getTrueTypeFromConditionalType(target as ConditionalType), RecursionFlags.Target, /*reportErrors*/ false)) {
result &= isRelatedTo(source, getFalseTypeFromConditionalType(target as ConditionalType), RecursionFlags.Target, /*reportErrors*/ false);
if (result) {
resetErrorInfo(saveErrorInfo);
return result;
}
}
}
if (localResult) {
resetErrorInfo(saveErrorInfo);
return localResult;
}
}
else if (target.flags & TypeFlags.TemplateLiteral) {
if (source.flags & TypeFlags.TemplateLiteral) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(12,20): error TS2345: Argument of type '"value"' is not assignable to parameter of type 'XX extends XX ? "value" : never'.
tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(28,20): error TS2345: Argument of type 'string' is not assignable to parameter of type 'never'.
tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(29,21): error TS2345: Argument of type 'string' is not assignable to parameter of type 'never'.
tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(33,22): error TS2345: Argument of type 'T | null' is not assignable to parameter of type 'null extends T | null ? any : never'.
Type 'null' is not assignable to type 'null extends T | null ? any : never'.
tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(34,23): error TS2345: Argument of type 'T | null' is not assignable to parameter of type '[null] extends [T | null] ? any : never'.
Type 'null' is not assignable to type '[null] extends [T | null] ? any : never'.
tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(39,3): error TS2322: Type '{ x: T; y: T; }' is not assignable to type 'T extends T ? { x: T; y: T; } : never'.
tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(46,3): error TS2322: Type 'string' is not assignable to type 'Foo<T>'.
tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(63,9): error TS2322: Type '{ a: number; b: number; }' is not assignable to type '[T] extends [[infer U]] ? U : { b: number; }'.
Expand All @@ -10,7 +15,7 @@ tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(116,3): error T
Type '(arg: any) => any' is not assignable to type 'InferBecauseWhyNotDistributive<Q>'.


==== tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts (8 errors) ====
==== tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts (11 errors) ====
export type FilterPropsByType<T, TT> = {
[K in keyof T]: T[K] extends TT ? K : never
}[keyof T];
Expand All @@ -23,6 +28,8 @@ tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(116,3): error T

export function func<XX extends string>(x: XX, tipos: { value: XX }[]) {
select(x, tipos, "value");
~~~~~~~
!!! error TS2345: Argument of type '"value"' is not assignable to parameter of type 'XX extends XX ? "value" : never'.
}

declare function onlyNullablePlease<T extends null extends T ? any : never>(
Expand All @@ -48,7 +55,13 @@ tests/cases/compiler/conditionalTypeAssignabilityWhenDeferred.ts(116,3): error T
function f<T>(t: T) {
var x: T | null = Math.random() > 0.5 ? null : t;
onlyNullablePlease(x); // should work
~
!!! error TS2345: Argument of type 'T | null' is not assignable to parameter of type 'null extends T | null ? any : never'.
Copy link
Member

Choose a reason for hiding this comment

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

This one is interesting - is this actually a distributive conditional type? Why is it deferred?

Copy link
Member Author

Choose a reason for hiding this comment

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

We always defer if either of the check and extends types contains generics. This is somewhat of a blunt instrument, and we could possibly do better in cases like this.

Copy link
Member Author

Choose a reason for hiding this comment

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

And by "contains generics" I mean we defer when isGenericType returns true for either of the check and extends types.

!!! error TS2345: Type 'null' is not assignable to type 'null extends T | null ? any : never'.
onlyNullablePlease2(x); // should work
~
!!! error TS2345: Argument of type 'T | null' is not assignable to parameter of type '[null] extends [T | null] ? any : never'.
!!! error TS2345: Type 'null' is not assignable to type '[null] extends [T | null] ? any : never'.
}

function f2<T>(t1: { x: T; y: T }, t2: T extends T ? { x: T; y: T } : never) {
Expand Down