Skip to content

Const indexed access issue β€” should attempt widening to a mapped typeΒ #51156

Description

Bug Report

Anders Hejlsberg (@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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions