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 relationship checking with keyof GenericMappedType as the source type #56246

Closed
Show file tree
Hide file tree
Changes from 6 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
55 changes: 27 additions & 28 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13984,6 +13984,27 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return isTypeAssignableTo(nameType, getTypeParameterFromMappedType(type)) ? MappedTypeNameTypeKind.Filtering : MappedTypeNameTypeKind.Remapping;
}

// generic mapped types that don't simplify or have a constraint still have a very simple set of keys - their nameType or constraintType.
// In many ways, this is a deferred version of what `getIndexTypeForMappedType` does to actually resolve the keys for _non_-generic types
function getGenericMappedTypeKeys(type: MappedType) {
const nameType = getNameTypeFromMappedType(type);
if (nameType && isMappedTypeWithKeyofConstraintDeclaration(type)) {
// we need to get the apparent mappings and union them with the generic mappings, since some properties may be
// missing from the `constraintType` which will otherwise be mapped in the object
const modifiersType = getApparentType(getModifiersTypeFromMappedType(type));
const mappedKeys: Type[] = [];
forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(
modifiersType,
TypeFlags.StringOrNumberLiteralOrUnique,
/*stringsOnly*/ false,
t => void mappedKeys.push(instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t))),
);
// We still need to include the non-apparent (and thus still generic) keys since when this gets used in comparisons the other side might include them
return getUnionType([...mappedKeys, nameType]);
}
return nameType || getConstraintTypeFromMappedType(type);
}

function resolveStructuredTypeMembers(type: StructuredType): ResolvedType {
if (!(type as ResolvedType).members) {
if (type.flags & TypeFlags.Object) {
Expand Down Expand Up @@ -22352,34 +22373,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return Ternary.True;
}
}
else if (isGenericMappedType(targetType)) {
// generic mapped types that don't simplify or have a constraint still have a very simple set of keys we can compare against
// - their nameType or constraintType.
// In many ways, this comparison is a deferred version of what `getIndexTypeForMappedType` does to actually resolve the keys for _non_-generic types

const nameType = getNameTypeFromMappedType(targetType);
const constraintType = getConstraintTypeFromMappedType(targetType);
let targetKeys;
if (nameType && isMappedTypeWithKeyofConstraintDeclaration(targetType)) {
// we need to get the apparent mappings and union them with the generic mappings, since some properties may be
// missing from the `constraintType` which will otherwise be mapped in the object
const modifiersType = getApparentType(getModifiersTypeFromMappedType(targetType));
const mappedKeys: Type[] = [];
forEachMappedTypePropertyKeyTypeAndIndexSignatureKeyType(
modifiersType,
TypeFlags.StringOrNumberLiteralOrUnique,
/*stringsOnly*/ false,
t => void mappedKeys.push(instantiateType(nameType, appendTypeMapping(targetType.mapper, getTypeParameterFromMappedType(targetType), t))),
);
// We still need to include the non-apparent (and thus still generic) keys in the target side of the comparison (in case they're in the source side)
targetKeys = getUnionType([...mappedKeys, nameType]);
}
else {
targetKeys = nameType || constraintType;
}
if (isRelatedTo(source, targetKeys, RecursionFlags.Target, reportErrors) === Ternary.True) {
return Ternary.True;
}
else if (isGenericMappedType(targetType) && isRelatedTo(source, getGenericMappedTypeKeys(targetType), RecursionFlags.Target, reportErrors) === Ternary.True) {
return Ternary.True;
}
}
}
Expand Down Expand Up @@ -22565,6 +22560,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}
else if (sourceFlags & TypeFlags.Index) {
const sourceType = (source as IndexType).type;
if (isGenericMappedType(sourceType) && isRelatedTo(getGenericMappedTypeKeys(sourceType), target, RecursionFlags.Source, reportErrors) === Ternary.True) {
return Ternary.True;
}
if (result = isRelatedTo(keyofConstraintType, target, RecursionFlags.Source, reportErrors)) {
return result;
}
Expand Down
80 changes: 80 additions & 0 deletions tests/baselines/reference/keyRemappingKeyofResult.errors.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
keyRemappingKeyofResult.ts(69,5): error TS2322: Type 'string' is not assignable to type 'keyof Remapped'.
Type '"whatever"' is not assignable to type 'unique symbol | "str" | DistributiveNonIndex<K>'.


==== keyRemappingKeyofResult.ts (1 errors) ====
const sym = Symbol("")
type Orig = { [k: string]: any, str: any, [sym]: any }

type Okay = Exclude<keyof Orig, never>
// type Okay = string | number | typeof sym

type Remapped = { [K in keyof Orig as {} extends Record<K, any> ? never : K]: any }
/* type Remapped = {
str: any;
[sym]: any;
} */
// no string index signature, right?

type Oops = Exclude<keyof Remapped, never>
declare let x: Oops;
x = sym;
x = "str";
// type Oops = typeof sym <-- what happened to "str"?

// equivalently, with an unresolved generic (no `exclude` shenanigans, since conditions won't execute):
function f<T>() {
type Orig = { [k: string]: any, str: any, [sym]: any } & T;

type Okay = keyof Orig;
let a: Okay;
a = "str";
a = sym;
a = "whatever";
// type Okay = string | number | typeof sym

type Remapped = { [K in keyof Orig as {} extends Record<K, any> ? never : K]: any }
/* type Remapped = {
str: any;
[sym]: any;
} */
// no string index signature, right?

type Oops = keyof Remapped;
let x: Oops;
x = sym;
x = "str";
}

// and another generic case with a _distributive_ mapping, to trigger a different branch in `getIndexType`
function g<T>() {
type Orig = { [k: string]: any, str: any, [sym]: any } & T;

type Okay = keyof Orig;
let a: Okay;
a = "str";
a = sym;
a = "whatever";
// type Okay = string | number | typeof sym

type NonIndex<T extends PropertyKey> = {} extends Record<T, any> ? never : T;
type DistributiveNonIndex<T extends PropertyKey> = T extends unknown ? NonIndex<T> : never;

type Remapped = { [K in keyof Orig as DistributiveNonIndex<K>]: any }
/* type Remapped = {
str: any;
[sym]: any;
} */
// no string index signature, right?

type Oops = keyof Remapped;
let x: Oops;
x = sym;
x = "str";
x = "whatever"; // error
~
!!! error TS2322: Type 'string' is not assignable to type 'keyof Remapped'.
!!! error TS2322: Type '"whatever"' is not assignable to type 'unique symbol | "str" | DistributiveNonIndex<K>'.
}

export {};
2 changes: 2 additions & 0 deletions tests/baselines/reference/keyRemappingKeyofResult.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ function g<T>() {
let x: Oops;
x = sym;
x = "str";
x = "whatever"; // error
}

export {};
Expand Down Expand Up @@ -97,5 +98,6 @@ function g() {
let x;
x = sym;
x = "str";
x = "whatever"; // error
}
export {};
3 changes: 3 additions & 0 deletions tests/baselines/reference/keyRemappingKeyofResult.symbols
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,9 @@ function g<T>() {

x = "str";
>x : Symbol(x, Decl(keyRemappingKeyofResult.ts, 65, 7))

x = "whatever"; // error
>x : Symbol(x, Decl(keyRemappingKeyofResult.ts, 65, 7))
}

export {};
5 changes: 5 additions & 0 deletions tests/baselines/reference/keyRemappingKeyofResult.types
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,11 @@ function g<T>() {
>x = "str" : "str"
>x : keyof { [K in keyof ({ [k: string]: any; str: any; [sym]: any; } & T) as K extends unknown ? {} extends Record<K, any> ? never : K : never]: any; }
>"str" : "str"

x = "whatever"; // error
>x = "whatever" : "whatever"
>x : keyof { [K in keyof ({ [k: string]: any; str: any; [sym]: any; } & T) as K extends unknown ? {} extends Record<K, any> ? never : K : never]: any; }
>"whatever" : "whatever"
}

export {};
84 changes: 84 additions & 0 deletions tests/baselines/reference/keyRemappingKeyofResult2.symbols
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//// [tests/cases/compiler/keyRemappingKeyofResult2.ts] ////

=== keyRemappingKeyofResult2.ts ===
// https://github.com/microsoft/TypeScript/issues/56239

type Values<T> = T[keyof T];
>Values : Symbol(Values, Decl(keyRemappingKeyofResult2.ts, 0, 0))
>T : Symbol(T, Decl(keyRemappingKeyofResult2.ts, 2, 12))
>T : Symbol(T, Decl(keyRemappingKeyofResult2.ts, 2, 12))
>T : Symbol(T, Decl(keyRemappingKeyofResult2.ts, 2, 12))

type ProvidedActor = {
>ProvidedActor : Symbol(ProvidedActor, Decl(keyRemappingKeyofResult2.ts, 2, 28))

src: string;
>src : Symbol(src, Decl(keyRemappingKeyofResult2.ts, 4, 22))

logic: unknown;
>logic : Symbol(logic, Decl(keyRemappingKeyofResult2.ts, 5, 14))

};

interface StateMachineConfig<TActors extends ProvidedActor> {
>StateMachineConfig : Symbol(StateMachineConfig, Decl(keyRemappingKeyofResult2.ts, 7, 2))
>TActors : Symbol(TActors, Decl(keyRemappingKeyofResult2.ts, 9, 29))
>ProvidedActor : Symbol(ProvidedActor, Decl(keyRemappingKeyofResult2.ts, 2, 28))

invoke: {
>invoke : Symbol(StateMachineConfig.invoke, Decl(keyRemappingKeyofResult2.ts, 9, 61))

src: TActors["src"];
>src : Symbol(src, Decl(keyRemappingKeyofResult2.ts, 10, 11))
>TActors : Symbol(TActors, Decl(keyRemappingKeyofResult2.ts, 9, 29))

};
}

declare function setup<TActors extends Record<string, unknown>>(_: {
>setup : Symbol(setup, Decl(keyRemappingKeyofResult2.ts, 13, 1))
>TActors : Symbol(TActors, Decl(keyRemappingKeyofResult2.ts, 15, 23))
>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --))
>_ : Symbol(_, Decl(keyRemappingKeyofResult2.ts, 15, 64))

actors: {
>actors : Symbol(actors, Decl(keyRemappingKeyofResult2.ts, 15, 68))

[K in keyof TActors]: TActors[K];
>K : Symbol(K, Decl(keyRemappingKeyofResult2.ts, 17, 5))
>TActors : Symbol(TActors, Decl(keyRemappingKeyofResult2.ts, 15, 23))
>TActors : Symbol(TActors, Decl(keyRemappingKeyofResult2.ts, 15, 23))
>K : Symbol(K, Decl(keyRemappingKeyofResult2.ts, 17, 5))

};
}): {
createMachine: (
>createMachine : Symbol(createMachine, Decl(keyRemappingKeyofResult2.ts, 19, 5))

config: StateMachineConfig<
>config : Symbol(config, Decl(keyRemappingKeyofResult2.ts, 20, 18))
>StateMachineConfig : Symbol(StateMachineConfig, Decl(keyRemappingKeyofResult2.ts, 7, 2))

Values<{
>Values : Symbol(Values, Decl(keyRemappingKeyofResult2.ts, 0, 0))

[K in keyof TActors as K & string]: {
>K : Symbol(K, Decl(keyRemappingKeyofResult2.ts, 23, 9))
>TActors : Symbol(TActors, Decl(keyRemappingKeyofResult2.ts, 15, 23))
>K : Symbol(K, Decl(keyRemappingKeyofResult2.ts, 23, 9))

src: K;
>src : Symbol(src, Decl(keyRemappingKeyofResult2.ts, 23, 45))
>K : Symbol(K, Decl(keyRemappingKeyofResult2.ts, 23, 9))

logic: TActors[K];
>logic : Symbol(logic, Decl(keyRemappingKeyofResult2.ts, 24, 17))
>TActors : Symbol(TActors, Decl(keyRemappingKeyofResult2.ts, 15, 23))
>K : Symbol(K, Decl(keyRemappingKeyofResult2.ts, 23, 9))

};
}>
>,
) => void;
};

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

=== keyRemappingKeyofResult2.ts ===
// https://github.com/microsoft/TypeScript/issues/56239

type Values<T> = T[keyof T];
>Values : Values<T>

type ProvidedActor = {
>ProvidedActor : { src: string; logic: unknown; }

src: string;
>src : string

logic: unknown;
>logic : unknown

};

interface StateMachineConfig<TActors extends ProvidedActor> {
invoke: {
>invoke : { src: TActors["src"]; }

src: TActors["src"];
>src : TActors["src"]

};
}

declare function setup<TActors extends Record<string, unknown>>(_: {
>setup : <TActors extends Record<string, unknown>>(_: { actors: { [K in keyof TActors]: TActors[K]; }; }) => { createMachine: (config: StateMachineConfig<Values<{ [K_1 in keyof TActors as K_1 & string]: { src: K_1; logic: TActors[K_1]; }; }>>) => void; }
>_ : { actors: { [K in keyof TActors]: TActors[K]; }; }

actors: {
>actors : { [K in keyof TActors]: TActors[K]; }

[K in keyof TActors]: TActors[K];
};
}): {
createMachine: (
>createMachine : (config: StateMachineConfig<Values<{ [K in keyof TActors as K & string]: { src: K; logic: TActors[K]; }; }>>) => void

config: StateMachineConfig<
>config : StateMachineConfig<Values<{ [K in keyof TActors as K & string]: { src: K; logic: TActors[K]; }; }>>

Values<{
[K in keyof TActors as K & string]: {
src: K;
>src : K

logic: TActors[K];
>logic : TActors[K]

};
}>
>,
) => void;
};

Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ type Str<T extends string> = T
type Bar<T> =
T extends Foo
? T['foo'] extends string
// Type 'T["foo"]' does not satisfy the constraint 'string'.
// Type 'string | undefined' is not assignable to type 'string'.
// Type 'undefined' is not assignable to type 'string'.(2344)
? Str<T['foo']>
: never
: never
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,6 @@ type Bar<T> =
? T['foo'] extends string
>T : Symbol(T, Decl(substitutionTypeForIndexedAccessType2.ts, 6, 9))

// Type 'T["foo"]' does not satisfy the constraint 'string'.
// Type 'string | undefined' is not assignable to type 'string'.
// Type 'undefined' is not assignable to type 'string'.(2344)
? Str<T['foo']>
>Str : Symbol(Str, Decl(substitutionTypeForIndexedAccessType2.ts, 2, 1))
>T : Symbol(T, Decl(substitutionTypeForIndexedAccessType2.ts, 6, 9))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@ type Bar<T> =

T extends Foo
? T['foo'] extends string
// Type 'T["foo"]' does not satisfy the constraint 'string'.
// Type 'string | undefined' is not assignable to type 'string'.
// Type 'undefined' is not assignable to type 'string'.(2344)
? Str<T['foo']>
: never
: never
1 change: 1 addition & 0 deletions tests/cases/compiler/keyRemappingKeyofResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ function g<T>() {
let x: Oops;
x = sym;
x = "str";
x = "whatever"; // error
}

export {};
Loading
Loading