-
Notifications
You must be signed in to change notification settings - Fork 12.2k
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
Optional chaining should narrow union types too #56264
Comments
This is the intended behavior because object types aren't sealed. You can legally write this code type Foo = { a: { b: string } } | { c: number }
let bar = { a: 0, c: 2 };
let foo: Foo = bar; which then crashes if run (thus should have a type error) foo?.a.toLowerCase(); |
Write the type like this instead: type Foo = { a: { b: string } } | { a?: undefined, c: number } Your scenario then works because you're ensuring that |
@ahejlsberg Technically |
Maybe this could be resolved if #12936 is implemented (some day). |
This issue has been marked as "Working as Intended" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
π Search Terms
optional chaining
,union type
β Viability Checklist
β Suggestion
It should be allowed to access deep property of a union variable with optional chaining.
Consider the example below,
TypeScript should be able to infer
foo.a?.b
correctly, but currently TypeScript throws an error instead.π Motivating Example
It would be useful for library users who want to access a property from a variable we don't have control over.
Here's an example with jscodeshift.
For TypeScript, it is so hard to work around with the type checker,
For JavaScript, we can just,
I don't know if this is a bug instead.
#40397 was discussing the same issue, which was labeled as "fixed". However, the attached code snippet doesn't work on TypeScript v5.2.2.
The text was updated successfully, but these errors were encountered: