8000 Allow to use null as discriminator for tagged union · Issue #24193 · microsoft/TypeScript · GitHub
[go: up one dir, main page]

Skip to content
Allow to use null as discriminator for tagged union #24193
Closed
@KSXGitHub

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

interface WithError {
    error: Error
    data: null
}

interface WithoutError<Data> {
    error: null
    data: Data
}

type DataCarrier<Data> = WithError | WithoutError<Data>

// MAIN FOCUS:
//   TypeScript should be able to deduce error's and data's
//   types in the following function 
function test<Data>(carrier: DataCarrier<Data>) {
    if (carrier.error === null) { // `error` property as disciminator
        const error: null = carrier.error // should work
        const data: Data = carrier.data // should work
    } else {
        const error: Error = carrier.error // should work
        const data: 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

      0