Skip to content

Union type doesn't match the description in the HandbookΒ #51062

Closed
@cnshenj

Description

@cnshenj

Bug Report

πŸ”Ž Search Terms

union; widen; type

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about union.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

The Handbook describes the union type:

A union type is a type formed from two or more other types, representing values that may be any one of those types.

This means if we define type T = A | B, then its value can be any of A's values, or any of B's values. It implicitly means that if a value is not of type A or B, it is not a valid T value.

However, the code below shows that the same value is considered not A and not B, but is A | B. This contradicts the Handbook. One of them needs to changed to match the other. To me, the Handbook seems to make more sense.

type A = { a: number };
type B = { b: number };

const a: A = { a: 0, b: 1 }; // Error, "b" not allowed
const b: B = { a: 0, b: 1 }; // Error, "a" not allowed
const ab: A | B = { a: 0, b: 1 }; // No error, although the value is not a valid A or B

πŸ™ Actual behavior

A value of A | B can be neither A nor B.

πŸ™‚ Expected behavior

A value of A | B should be either A or B.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions