microsoft / microsoft/TypeScript
Discriminated unions is not work when field key is number
Open
Nobody has claimed this yet.
Awaiting More Feedback
Suggestion
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
🔎 Search Terms
- discriminated unions, "discriminated-unions"
- "numbers as keys in object", "number key"
- "type guard"
🕗 Version & Regression Information
- This is a crash
⏯ Playground Link
💻 Code
type A = number[] | string[]
type B = { 0: number, a: 1 } | { 0: string, a: '1' }
declare const a: A
declare const b: B
if (typeof a[0] === 'number') {
console.log(a)
// ^? A
}
if (typeof b['a'] === 'number') {
console.log(b)
// ^? { 0: number, a: 1 }
}
if (typeof b['0'] === 'number') {
console.log(b)
// ^? B
}
if (typeof b[0] === 'number') {
console.log(b)
// ^? B
}
🙁 Actual behavior
Unable to type guard b as an option of the union type B.
🙂 Expected behavior
Type b as { 0: number, a: 1 } when type guarding it with typeof b['0'] === 'number'.
Additional information about the issue
- microsoft/TypeScript#55632
- microsoft/TypeScript#55766
- microsoft/TypeScript#55961
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked TypeScript Playground example and compare the existing behavior for string and numeric keys. Read the related issues microsoft/TypeScript#55632, #55766, and #55961 to understand the type-guard context. Done means typeof b['0'] === 'number' narrows B to { 0: number, a: 1 } without breaking the other examples.
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
- 35/100