Closed
Description
Bug Report
@ahejlsberg This issue seems nearly identical to #47368, but this time for const object types which are assignable to the mapped type.
π Search Terms
const indexed access; object literal indexed access; object literal widen; widen mapped type
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about indexed access.
β― Playground Link
Playground link with relevant code
π» Code
type ArgMap = { a: number, b: string };
type Func<K extends keyof ArgMap> = (x: ArgMap[K]) => void;
type Funcs = { [K in keyof ArgMap]: Func<K> };
const funcs = {
a: (x: number) => {},
b: (x: string) => {},
};
function f1<K extends keyof ArgMap>(key: K, arg: ArgMap[K]) {
funcs[key](arg);
}
function f2<K extends keyof ArgMap>(key: K, arg: ArgMap[K]) {
const func = funcs[key]; // Type Funcs[K]
func(arg);
}
function f3<K extends keyof ArgMap>(key: K, arg: ArgMap[K]) {
const func: Func<K> = funcs[key]; // Error, Funcs[K] not assignable to Func<K>
func(arg);
}
π Actual behavior
Unexpected error in example above.
It's unexpected because throwing away type information makes this type check correctly, by widening with either const funcs: Funcs
(all examples) or const func: Funcs[K]
(in f2). So the compiler actually is able to confirm that indexed type is assignable to the mapped type, it just doesn't try without being explicitly prompted.
π Expected behavior
No errors in example above.