Skip to content

Type Narrowing for discriminated unions not narrow enough #12955

Description

@stevekane

TypeScript Version: 2.2.0-dev.20161215

Code

typeKinded={kind: 0}|{kind: 1}functionforKinded(k: Kinded){if(k.kind==0)console.log('ZERO')elseconsole.log('ONE')}constk={kind: 0}constk2: Kinded={kind: 0}forKinded(k)// nope. it has already guessed that k is of type { kind: number }forKinded(k2)// works. specifying type obviously does the right thingforKinded({kind: 0})// works. it understands that the argument literal is of type { kind: 0 }

Expected behavior:
Would expect it to try narrowing the type to a literal from the enumeration if the general enum doesn't satisfy other type expectations.
Actual behavior:
When defined as a literal function argument, typescript further narrows the type, otherwise it does not? This seems perhaps non-awesome or at least the compiler maybe ought to try further narrowing as a constraint to see if it type-checks the entirety of the program?

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