You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Intersection on indexing a conditional type objectΒ #55804
exportconstKEYS=['cat','dog','fox','orca','ox']asconstexportconstKEYS_TYPE_MAPPING={cat: 'options',dog: 'options',fox: 'options',orca: 'range',ox: 'range',}asconstexporttypeKeyValue={options: string[]range: {min?: number;max?: number}}exporttypeItems={[Kin(typeofKEYS)[number]]?: KeyValue[(typeofKEYS_TYPE_MAPPING)[K]]}letanimals: Items={cat: ["x","y","x"]}for(letkeyofKEYS){// union of possible value types in 'KeyValue'letx=animals[key]// ERROR: becomes an intersection when trying to set the valueanimals[key]=x}
π Actual behavior
After creating a object type where each key has a mapped value type, an intersection of said types is created which causes object[key] to not be the same type as object[key] when setting a value at an index of the object.
It should not be an intersection type since the value types never overlap.
π Expected behavior
I expected the type of 'x' (when setting it as the value of object[key]) to be the same type as 'object[key]'. Since they both reference the same index in the same object. Also I would expect the type of 'x' and 'object[key]' to be a union of the value types since they do not overlap.
See #55756 (comment) and #30769. When key is union-typed, as it is here, the compiler doesnβt understand that key refers to the same property in both places. The intersection type arises because thatβs the only type thatβs known to be valid for any possible key.
Interesting, I assume the most optimal work around would be to explicitly type each key value as the union then? Unless there's something else that I'm not aware of.
Activity
fatcerberus commentedon Sep 20, 2023
See #55756 (comment) and #30769. When
keyis union-typed, as it is here, the compiler doesnβt understand thatkeyrefers to the same property in both places. The intersection type arises because thatβs the only type thatβs known to be valid for any possiblekey.MaximilianFullStack commentedon Sep 20, 2023
Interesting, I assume the most optimal work around would be to explicitly type each key value as the union then? Unless there's something else that I'm not aware of.
Andarist commentedon Sep 21, 2023
There might be a way to write this in terms of correlated unions created out of mapped types: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-6.html#indexed-access-inference-improvements