Microsoft/TypeScript

Destructuring a possibly `undefined` object not caught, throws an error at runtime

Open

#60,179 创建于 2024年10月9日

在 GitHub 查看
 (3 评论) (1 反应) (0 负责人)TypeScript (6,726 fork)batch import
BugDomain: check: Control FlowHelp Wanted

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

🔎 Search Terms

destructuring, Cannot destructure as it is undefined, optional chaining destructuring

🕗 Version & Regression Information

  • This changed between versions ______ and _______
  • This changed in commit or PR _______
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
  • I was unable to test this on prior versions because _______

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.6.2#code/MYewdgzgLgBAlmADgVygLhgbwLACgYEwCGA-BpjAEZlYzAbQBOCA5jAL4d6cC8tRGZGAAmAUwBmCUcK648oSLAoA6VZQ4w+CFFGWlllIA

💻 Code

const input: {
    a?: { b?: { c: string } }
} = { a: undefined }

const { ...b } = input.a?.b

🙁 Actual behavior

No error reported by TypeScript.

🙂 Expected behavior

TypeScript should have an indicative error, since this expression might result in undefined, which cannot be destructured.

Similar to this: Image

Rest types may only be created from object types.(2700)

Additional information about the issue

The error in the JavaScript being ran is:

Uncaught TypeError: Cannot destructure '(intermediate value)' as it is undefined.

贡献者指南