Skip to content

Inference doesn't work with union types #2264

Closed
@zpdDG4gta8XKpMCd

Description

@zpdDG4gta8XKpMCd

I don't understand what is wrong with the following piece of code. It's a very basic scenario that I wish I could have since now union types are here. Please let me know what I am doing wrong:

interface Y { 'i am a very certain type': Y }
var y : Y = <Y> undefined;
function destructure<a, r>(
    something: a | Y,
    haveValue: (value: a) => r,
    haveY: (value: Y) => r
) : r {
    return something === y ? haveY(y) : haveValue(<a> something);
}

var value = Math.random() > 0.5 ? 'hey!' : <Y> undefined;

console.log(destructure(value, text => 'string', y => 'other one')); // <-- complete mess and failure

At playground: http://www.typescriptlang.org/Playground#src=interface%20Y%20%7B%20'i%20am%20a%20very%20certain%20type'%3A%20Y%20%7D%0Avar%20y%20%3A%20Y%20%3D%20%3CY%3E%20undefined%3B%0Afunction%20destructure%3Ca%2C%20r%3E(%0A%09something%3A%20a%20%7C%20Y%2C%0A%09haveValue%3A%20(value%3A%20a)%20%3D%3E%20r%2C%0A%09haveY%3A%20(value%3A%20Y)%20%3D%3E%20r%0A)%20%3A%20r%20%7B%0A%09return%20something%20%3D%3D%3D%20y%20%3F%20haveY(y)%20%3A%20haveValue(%3Ca%3E%20something)%3B%0A%7D%0A%0Avar%20value%20%3D%20Math.random()%20%3E%200.5%20%3F%20'hey!'%20%3A%20%3CY%3E%20undefined%3B%0A%0Aconsole.log(destructure(value%2C%20text%20%3D%3E%20'string'%2C%20b%20%3D%3E%20'other%20one'))%3B%20%2F%2F%20%3C--%20complete%20mess%20and%20failure%0A

Related question at StackOverflow: http://stackoverflow.com/questions/28931221/whats-the-use-of-union-types-in-typescript

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions