Skip to content

Optional Chaining and Type Narrowing #33736

@arciisine

Description

@arciisine

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.

Metadata

Metadata

Assignees

Labels

DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions