-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Empty array in union with tuple doesn't infer undefined on indexed access #47531
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This would not be a problem if an empty array was inferred as |
Workaround: const data = ['A'] as const;
const a = Math.random() > 0.5 ? [] as const : data;
a[0].trim(); // TS2532: possibly undefined |
@fatcerberus yup. From the practical standpoint, if I know I need this workaround here and now, it means I anticipate possible type unsafety and have double checked my code already. However, if I'm unaware I'm doing something wrong, it would also not occur to me to do So my point is that this should be as automated (inferred) as possible. |
This is pretty messed up; we shouldn't be presenting a |
@RyanCavanaugh A surefire way to get a function fooey() { return []; }
const foo = fooey();
// ^? const foo: never[] |
#50474 was marked as a duplicate of this, but if so, then the problem doesn't seem to have much to do with const nums: { [k: string]: number } = Math.random() < 0.5 ? { a: 1 } : { b: 2 };
const str = { a: "hello" }
// with --noUncheckedIndexedAccess on
const hmm = (Math.random() < 0.5 ? nums.a : str.a) // string | number | undefined
const wha = (Math.random() < 0.5 ? nums : str).a // string | number <-- 😕 Is this a bug? If so, does it belong here in #47531 or somewhere else? |
Bug Report
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 asnever[]
in many scenarios, thus allowing type-unsafe code. Example:🔎 Search Terms
Tuple, union, empty array, infer, noUncheckedIndexedAccess
🕗 Version & Regression Information
never
,tuple
,array
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
Compiles well, breaks at runtime
🙂 Expected behavior
Compile-time error that
tuple[0]
is possibly undefinedThe text was updated successfully, but these errors were encountered: