Skip to content

Empty array in union with tuple doesn't infer undefined on indexed access #47531

Open
@amakhrov

Description

@amakhrov

Bug Report

declare const tuple: never[] | [string];

tuple[0].length // no compile-time error :(

Playground
Note that noUncheckedIndexedAccess is enabled - but doesn't make any difference in this case.

The reason it is a problem is that [] is inferred as never[] in many scenarios, thus allowing type-unsafe code. Example:

const data = ['A'] as const;

// inferred as `never[] | ['A']
const a = Math.random() > 0.5 ? [] : data;

a[0].length; // can be undefined, but no compiler error

🔎 Search Terms

Tuple, union, empty array, infer, noUncheckedIndexedAccess

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about never, tuple, array

⏯ Playground Link

Playground link with relevant code

💻 Code

declare const tuple: never[] | [string];

tuple[0].length // no compile-time error :(

🙁 Actual behavior

Compiles well, breaks at runtime

🙂 Expected behavior

Compile-time error that tuple[0] is possibly undefined

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions