Skip to content

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

@DetachHead

Description

@DetachHead

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({})
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions