Repository navigation
Closed
Labels
Design LimitationConstraints of the existing architecture prevent this from being fixed
Description
Bug Report / Feature Request
When indexing a mapped type that is meant to have the same keys as an original type, the compiler emits errors when using a generic type which is a key of the original type:
Playground Link with Demonstration
Static Code Sample
export interface Original {
prop1: {
subProp1: string,
subProp2: string
},
prop2: {
subProp3: string,
subProp4: string
}
}
export type KeyOfOriginal = keyof Original;
export type NestedKeyOfOriginalFor<T extends KeyOfOriginal> = keyof Original[T]
export const getStringFromOriginal = <K extends KeyOfOriginal, N extends NestedKeyOfOriginalFor<K>>(original: Original, key: K, nestedKey: N): Original[K][N] {
return original[key][nestedKey];
}
export type SameKeys<T> = {
[K in keyof T]: {
[K2 in keyof T[K]]: number;
}
}
export type MappedFromOriginal = SameKeys<Original>;
/**
* This method should work, as K and N are guaranteed to be valid keys of both Original and MappedFromOriginal
*
* The way the types are setup, it is invalid to construct an instance of MappedFromOriginal which has extra properties or is missing a property
*
* This example also works if I don't use nested keys, just one level of key mapping is fine. 2 levels of key mapping breaks.
*/
export const getStringAndNumberFromOriginalAndMapped =
<K extends KeyOfOriginal, N extends NestedKeyOfOriginalFor<K>>(
original: Original,
mappedFromOriginal: MappedFromOriginal,
key: K, nestedKey: N
): [Original[K][N], MappedFromOriginal[K][N]] => { // Type 'N' cannot be used to index type 'SameKeys<Original>[K]'
return [original[key][nestedKey], mappedFromOriginal[key][nestedKey]] // Type 'N' cannot be used to index type 'SameKeys<Original>[K]'
}Metadata
Metadata
Assignees
Labels
Design LimitationConstraints of the existing architecture prevent this from being fixed
Activity
RyanCavanaugh commentedon May 6, 2021
TS doesn't understand that, at a higher level, these keys are actually the same. You can write this for the desired behavior as
00benallen commentedon May 6, 2021
Ryan Cavanaugh (@RyanCavanaugh) I'll try this when I get into work tomorrow, but I guess the question is, COULD TS understand this without being explicitly told?
RyanCavanaugh commentedon May 7, 2021
Maybe? I doubt anything is truly impossible. Types like this are relatively rare and can be written in proposed form without loss of generality, so it doesn't seem worth it to add a concept of "same keys but different property types" to the language to accommodate this. I'm not even 100% convinced the given function is truly sound without the added intersections.