Skip to content
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

exactOptionalPropertyTypes #686

Open
981377660LMT opened this issue Jan 2, 2025 · 1 comment
Open

exactOptionalPropertyTypes #686

981377660LMT opened this issue Jan 2, 2025 · 1 comment

Comments

@981377660LMT
Copy link
Owner

No description provided.

@981377660LMT
Copy link
Owner Author

可选属性的“精确性”exactOptionalPropertyTypes(TS 4.4+)

exactOptionalPropertyTypes 可以让 TS 更精准地区分“确实存在但为 undefined”与“属性根本没定义”。开启后,? 属性就真的表示“此属性可能不存在”,而不是“存在且可以是 undefined”。示例:

{
  "compilerOptions": {
    "exactOptionalPropertyTypes": true
  }
}
interface Test {
  foo?: string // 要么完全没有 'foo',要么有 'foo' 并且是 string
}

const t1: Test = {}
const t2: Test = { foo: undefined }
// Error: foo 不可为 undefined,除非你写 `foo?: string | undefined`
  • 这能更严格地防范一些“属性存在但值是 undefined”的误用,也让你的接口定义更贴近实际语义。
  • 如果想兼容以前的宽松写法,需要在属性类型里手动加 | undefined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant