-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Closed
Labels
DeclinedThe issue was declined as something which matches the TypeScript visionThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
Search Terms
Optional Chaining
Suggestion
Currently I use a pattern of an in
check with a ternary to narrow type on optional fields. With the new optional chaining, it would be great if the type narrowing could occur as the optional chain is progressed.
Use Cases
The primary use here is for type narrowing on union types without the need for extra boilerplate.
Examples
Current method of using the in
operator for type narrowing.
type Header = { headers: Record<string, any> };
type Options = { config : any };
function getHeader(input: Header | Options, key: string, def?: any) {
return ('headers' in input ? input.headers[key] : undefined) || def;
}
Improved syntax given optional chaining
type Header = { headers: Record<string, any> };
type Options = { config : any };
function getHeader(input: Header | Options, key: string, def?: any) {
return input.headers?.[key] ?? def;
}
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, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
merongmerongmerong, Cryrivers, IllusionMH, ElianCordoba, maximeg and 27 more
Metadata
Metadata
Assignees
Labels
DeclinedThe issue was declined as something which matches the TypeScript visionThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScriptAn idea for TypeScript