Skip to content

Using type alias for record prevents compiler from inferring generic function argument correctlyΒ #54000

Closed as not planned
@yonigibbs

Description

@yonigibbs

Bug Report

πŸ”Ž Search Terms

Record, type alias, infer, parameter, generic

πŸ•— Version & Regression Information

  • This won't compile
  • This changed between versions 4.2.3 and 4.3.5

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

function foo<T>(record: Record<string, T>, entity: T) { }

type StringArrayRecord = Record<string, string[]>;

function test() {
    const working: Record<string, string[]> = {};
    foo(working, []); // Compiles

    const broken: StringArrayRecord = {};
    foo(broken, []); // Does not compile
}

πŸ™ Actual behavior

When using a type alias (StringArrayRecord in the example above), I cannot pass [] into function foo as the compiler can't infer that this is meant to be an array of strings. But if instead of the type alias I use the full Record definition, it does seem to infer it correctly, so I can pass in [].

πŸ™‚ Expected behavior

I'd expect the same behaviour in both cases. i.e. whether I use the type alias or the Record declaration I'd expect it either to compile or not compile (ideally compile of course). The issue in my opinion is that the introduction of a type alias seems to stop the compiler being able to infer the type.

Asked originally on StackOverflow: https://stackoverflow.com/questions/76090127/typescript-fails-to-infer-type-correctly-when-type-alias-used. There's a bit more info there showing that this doesn't seem to be related to the fact that the generic type parameter is an array.

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions