Open
Description
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