-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Empty array ([]
) inferred to be never[]
instead of []
or undefined[]
#51979
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
[]
) inferred to be never[]
instead of undefined[]
[]
) inferred to be never[]
instead of []
or undefined[]
Working as intended. In this context The |
@tylim88 It’s not really |
I see, thx for your explanation after evolve: |
The JS code is obviously buggy, the conditional assignment to Can anyone please help me understand why the runtime error is not a problem? In fact, even a type of |
That's completely unrelated to the const ret = Math.random() > 0.5 ? ['foo', 'bar'] as const : [] as any[];
// ^? const ret: any[] | readonly ['foo', 'bar']
const foo: string = ret[0]
const bar: string = ret[1]
// STILL throws a runtime error half the time.
console.log(
foo.toUpperCase(),
bar.toLocaleLowerCase()
) |
In fact Not that I'm actively rooting for |
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
I ran into this behavior where TypeScript infers that an empty array (literal
[]
) to be of typenever[]
, which it interprets to never happen and thus to be of no sigificance.Runtime errors then ensue.
🔎 Search Terms
"never[]" array
🕗 Version & Regression Information
Affects all versions from 3.5.1 through 4.9.4 (and the nightly)
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
I get a TS error on the
@ts-expect-error
comment as theret
tuple is inferred to be effectively always['foo', 'bar']
...and then I get runtime errors once I try and do
.toUpperCase()
on the (sometimesundefined
) values.🙂 Expected behavior
I'd expect the inferred type of
ret
to be something likereadonly ['foo', 'bar'] | []
or possiblyreadonly ['foo', 'bar'] | | Array<undefined>
.To fix this I have to explicitly change the first line to either:
…or:
The text was updated successfully, but these errors were encountered: