Skip to content

boolean is not assignable to false in type union discriminator field #30518

@TomasHubelbauer

Description

@TomasHubelbauer

TypeScript Version:

3.3.4000

Search Terms:

I used the search results provided when typing this issue's title and collected the results in the Related Issues section.

Code

type T1 = { flag: true; } | { flag: false; };
type T2 = true | false;
const flag = confirm('true | false');
const demo1: T1 = { flag };
const demo2: T2 = flag;

type T3 = { flag: true; value: 'a' | 'b' | 'c'; } | { flag: false; value: 'a' | 'b'; };
const value = 'a'; // Matches `'a' | 'b'`
const demo3: T3 = { flag, value: 'a' };

Expected behavior:

The code compiles with no errors.

Actual behavior:

The compiler displays an error on demo1 and demo3 lines, saying that boolean is not assignable to false. For this error to go away, one has to wrap the line in an if-else statement, passing a literal true in the if branch and false in the else branch.

The TypeScript compiler inference is probably not realizing that the rest of the union type members are compatible whichever way flag goes.

Playground Link:

TypeScript Playground

My repro repo

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions