Skip to content

Type 'boolean' is not assignable to type 'true' when constructing discriminated union variant #10657

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
deadalusai opened this issue Sep 1, 2016 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@deadalusai
Copy link

TypeScript Version: 2.0.2 RC

Code

export interface Some<T> {
    is_some: true;
    value: T;
}

export interface None { 
    is_some: false;
}

// fails typecheck
var a: Option<number> = { is_some: true, value: 1 };

Expected behavior:

Expected to pass typechecking.

Actual behavior:

The following error is raised:

src/option.ts(13,5): error TS2322: Type '{ is_some: boolean; value: number; }' is not assignable to type 'Option<number>'.
  Type '{ is_some: boolean; value: number; }' is not assignable to type 'Some<number>'.
    Types of property 'is_some' are incompatible.
      Type 'boolean' is not assignable to type 'true'.

Adding a cast of the boolean value to type true appears to fix the error:

// working example
var a: Option<number> = { is_some: <true> true, value: 1 };

I encountered this problem when experimenting with the following function. A version of the code which uses strings as the discriminator works without casts. Another version which uses value: null as the discriminator in the None case also works.

// failing example
export function map<T, N>(opt: Option<T>, fn: (value: T) => N): Option<N> {
    if (opt.is_some) {
        return { is_some: true, value: fn(opt.value) };
    }
    else {
        return { is_some: false }; 
    }
}
@yortus
Copy link
Contributor

yortus commented Sep 1, 2016

Duplicate of #10432. The PR in #10577 should fix this.

@deadalusai
Copy link
Author

Referenced issue looks to be identical - even the Same code sample. Closing as dupe.

@mhegazy mhegazy added the Duplicate An existing issue was already created label Sep 1, 2016
@tcoopman
Copy link

I have something similar in typescript 2.4.2, but it looks like it's only when I have return in a promise. Casting the boolean type to true or false fixes the problem.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants