-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Optional chaining discards contextual type data #57645
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
Comments
Narrowing doesn't really have a way to represent "this or the other thing must be undefined" in a way that can be propagated around - it has to make a definitive determination about a particular variable. |
I see. So when we have some type guard around a property access, e.g. If that's the case, I think the "either // I'm making the (probably false) assumption that TypeScript can recognize the law of excluded
// middle between Nullish<T> and NonNullable<T>
// `any` is a corner case, but I don't think that it needs to be handled any differently
type Nullish<T> = T & (null | undefined);
interface Foo {
bar?: Array<number>;
}
const foo = undefined as Foo | undefined;
if (!foo?.bar) {
type NarrowedFoo =
// foo is nullish
| Nullish<typeof foo>
// xor foo.bar's type is nullish
| { bar: Nullish<NonNullable<typeof foo>["bar"]> };
// foo ought to have type `NarrowedFoo`, but this assignment causes a type checker error
const narrowedFoo: NarrowedFoo = foo;
} |
This would require #42384. Type narrowing operations on |
This issue has been marked as "Design Limitation" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
🔎 Search Terms
contextual type
optional chaining
subtype reduction
control flow analysis
🕗 Version & Regression Information
Optional chaining was introduced in 3.7, and 3.7 has the same behavior.
⏯ Playground Link
https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGIHt3IN4ChnIBGcUA-AFzICCUUcAngDwgCuAtodAHwDcuAvrgToQAZzDIYmZAF5kLEABMIMUBEXI4otNIA+8pSrWK+wGMgAUAQinpSAOmJQAlDnzIA9B+QRgYABbQktLoUEQkyP5ayABucAA2LCgABgrKqiDqye7CYhIScrYOTnwEXsgAKsii-ugs8RqcyGD0AA4paUaZitkELe2Vss1tEOjmYKXIueLhAF6UFgAelDR0TKwc3Mj6nRnqrjJcsejAGnJLlBUHR3gEBNPo8RD20FChFgBEAcDaWqLAAHMQGwIOBqrV6ooQAByCTCNitYBPD7OSb8PiCIA
💻 Code
🙁 Actual behavior
Type
T
has typeArray<number> | undefined
, even though the conditional implies that the value oft
is falsy.🙂 Expected behavior
The compiler should say that
foo.bar
is undefined in the scope of the then branch of the if statement.Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: