Microsoft/TypeScript

Unions seem to sidestep `--noUncheckedIndexedAccess` and lose the possibility of undefined

Open

#61,225 建立於 2025年2月19日

在 GitHub 查看
 (0 留言) (3 反應) (0 負責人)TypeScript (6,726 fork)batch import
BugDomain: flag: noUncheckedIndexedAccessHelp Wanted

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 PR)

描述

🔎 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

💻 Code

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

貢獻者指南