-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Closed
Labels
CommittedThe team has roadmapped this issueThe team has roadmapped this issueFixedA PR has been merged for this issueA PR has been merged for this issueHelp WantedYou can do thisYou can do thisSuggestionAn idea for TypeScriptAn idea for TypeScript
Milestone
Description
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
Labels
CommittedThe team has roadmapped this issueThe team has roadmapped this issueFixedA PR has been merged for this issueA PR has been merged for this issueHelp WantedYou can do thisYou can do thisSuggestionAn idea for TypeScriptAn idea for TypeScript