Skip to content

Allow to use null as discriminator for tagged union #24193

Description

@KSXGitHub

Search Terms

Suggestion

Right now, even with strictNullChecks is set to true, null cannot be used as a discriminator for tagged union.

Use Cases

Recently, I made a pull request for @types/node in which I let spawnSync returns a tagged union with error property as discriminator.

Examples

interfaceWithError{error: Errordata: null}interfaceWithoutError<Data>{error: nulldata: Data}typeDataCarrier<Data>=WithError|WithoutError<Data>// MAIN FOCUS:// TypeScript should be able to deduce error's and data's// types in the following function functiontest<Data>(carrier: DataCarrier<Data>){if(carrier.error===null){// `error` property as disciminatorconsterror: null=carrier.error// should workconstdata: Data=carrier.data// should work}else{consterror: Error=carrier.error// should workconstdata: null=carrier.data// should work}}

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. new expression-level syntax)

Metadata

Metadata

Assignees

No one assigned

    Labels

    CommittedThe team has roadmapped this issueFixedA PR has been merged for this issueHelp WantedYou can do thisSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions