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

narrowing of property should also narrow its parent when optional chaining #49187

Closed
5 tasks done
DetachHead opened this issue May 20, 2022 · 1 comment
Closed
5 tasks done

Comments

@DetachHead
Copy link
Contributor

Suggestion

πŸ” Search Terms

narrowing optional chaining

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

when narrowing a property in an object, there are often other things it should be able to narrow as well. for example, when narrowing foo?.bar to a non-undefined type, it should also narrow foo to not be undefined

πŸ“ƒ Motivating Example

declare const foo: {
  bar: number[]
} | undefined

if (Array.isArray(foo?.bar)) {
  foo.bar //error: Object is possibly 'undefined'
}

πŸ’» Use Cases

i'm trying to conditionally modify an array, but only if its parent property is present. currently, i have to use ! to tell the compiler that it's not undefined, which isn't ideal:

if (
  itemDefinition.request === undefined ||
  typeof itemDefinition.request.url === 'string'
)
  return itemDefinition
const newItemDefinition = cloneDeep(itemDefinition)
if (Array.isArray(newItemDefinition.request!.url)) {
  newItemDefinition.request!.url.push({})
}
@MartinJohns
Copy link
Contributor

This sounds like a duplicate of #34974 to me.

@DetachHead DetachHead closed this as not planned Won't fix, can't repro, duplicate, stale May 20, 2022
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

2 participants