-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Type narrowing on a property does not narrow the type of the parent #50651
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
Used search terms: Duplicate of #42384. |
Looks like it's not a bug then, thanks @MartinJohns |
Yeah, if you need to narrow-by-property, you should use a discriminated union. Those exist as a trade-off, if this kind of thing worked in the general case, you wouldn't need them 😉 https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions |
My use case here was for a single type that has an optional property, so there is no need to make a discriminated union using a different property. For a single property this can actually be solved somewhat easily, but I thought this was supposed to work out of the box. |
Though not a bug, seems like a valid request still. Related to #42384, but slightly different. In the other issue, it’s talking about inferring (discriminating) the type of the parent based on properties of the parent, while this one is talking about narrowing the type of the parent's properties. Seems a perfectly valid use case that should work out of the box: type Nest = {
nested?: {}
}
function doSomething(n: Nest & { nested: object }) {}
declare const n: Nest
if (n.nested) {
doSomething(n) // Error
doSomething({ ...n }) // Error
doSomething({ nested: n.nested }) // Works, but loses object identity
} It seems obvious that inside the Whether this is working as intended or not, there’s obviously a gap there that at least can be explored. Should this issue be reopened? Another issue created to track this as a feature request instead? |
Bug Report
🔎 Search Terms
type narrowing
narrowing property
narrowing nested
🕗 Version & Regression Information
Locally I noticed this on versions 4.7.4 and 4.8.2.
It also happens on every version available on the playground, from 3.3.3 up to nightly (4.9.0-dev.20220905).
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
Type narrowing should happen on the property and the parent variable, allowing
f
to be passed totakesFooWithBaz
🙂 Expected behavior
The property
f.baz
is narrowed to not be undefined, but the propertybaz
of the type off
remains asstring | undefined
.The text was updated successfully, but these errors were encountered: