-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed as not planned
Closed as not planned
Copy link
Description
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
Labels
No labels