microsoft / microsoft/TypeScript
Unions seem to sidestep `--noUncheckedIndexedAccess` and lose the possibility of undefined
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
### 🔎 Search Terms
noUncheckedIndexedAccess, union, undefined
### 🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about `--noUncheckedIndexedAccess`
### ⏯ Playground Link
[Playground link](https://www.typescriptlang.org/play/?noUncheckedIndexedAccess=true#code/MYewdgzgLgBGCuBbCAuGBvGBtA1m6ATgJZgDmAumgogEYCmBMAvjALwwCyAhlABYB0BLmAAmIRAAoAlDAA8MAAz8ArDAD8GGFzQBGZjDSYaaAEzMA3AChQkWITabtMAES86AG3chnzS5YD0-jAA7kR8MAC0EWAgAKpgwG7AOHQiAJKidAAeqQCCwMB0EBAw4Nbg0DC8iIgOEtx8gsJikjLySqoa1BD8XAYwhL0ygQNQxGQwAD5wSPSM0-CZAGYkqeW2Ibx97PU8AkKi4tJyiirqM8j9hFK9MCOEJKRTF3N+QA)
### 💻 Code
```ts
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 <-- 😕
```
### 🙁 Actual behavior
The type of `wha` is `string | number`, completely ignoring the possibility that it might be `undefined`, even though `--noUncheckedIndexedAccess` is enabled. Looks like unions of types with index signatures and known keys lose the `--noUncheckedIndexedAccess` behavior.
### 🙂 Expected behavior
`wha` should be of type `string | number | undefined`, just like `hmm`, since indexed access into a union should look like a union of indexed accesses.
### Additional information about the issue
This is related to #50474. It’s also related to #47531, which had specifically to do with `never[]` and so the focus was on avoiding `never[]` as opposed to investigating what happened to the indexed access. ( https://github.com/microsoft/TypeScript/issues/47531#issuecomment-1229522810 )
Ran into this when looking at [a Stack Overflow question](https://stackoverflow.com/q/79451704/2887218)
Contributor guide
Research direction
Start with the linked TypeScript Playground reproduction using --noUncheckedIndexedAccess, and compare the two indexed-access expressions in the issue. The issue names no repository file or test; trace how indexed access is resolved for unions, then add coverage showing that the second expression includes undefined and run the relevant compiler tests.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100