Skip to content

Order of ReadonlySet/ReadonlyMap in union causes differing key inferenceΒ #52313

Open
@jakebailey

Description

@jakebailey

Bug Report

πŸ”Ž Search Terms

ReadonlyMap ReadonlySet key inference

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried.

⏯ Playground Link

Playground Link

πŸ’» Code

declare const map: Map<string, number>;


declare function forEachKey<K, T>(map: ReadonlySet<K> | ReadonlyMap<K, any>, callback: (key: K) => T | undefined): T | undefined;

forEachKey(map, (key) => {}) // Error passing "map", key type is wrong (number??)

forEachKey<string, void>(map, (key) => {}) // OK; no error, key type is string


// Now, flip the union order in the parameter's type.
declare function forEachKey2<K, T>(map: ReadonlyMap<K, any> | ReadonlySet<K>, callback: (key: K) => T | undefined): T | undefined;

forEachKey2(map, (key) => {}) // Okay?

forEachKey2<string, void>(map, (key) => {}) // Still okay.

πŸ™ Actual behavior

The order of the union appears to matter, breaking inference and erroring on valid code. Swapping the union order allows the code to compile.

πŸ™‚ Expected behavior

All of this should compile; the union ordering should not matter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptHas ReproThis issue has compiler-backed repros: https://aka.ms/ts-reprosUnion Order DependenceTS behavior is not supposed to depend on union order, but sometimes does

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions