Skip to content
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

Type inference - code after early return from an 'if' should infer the same type as the 'else' block would #8886

Closed
lanzkron opened this issue May 30, 2016 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@lanzkron
Copy link

Version 1.8

First of all I'm sorry if I get the jargon wrong, I'm new to typescript (I tried to search for this issue and failed, I may have used the wrong search terms).

When using type guards, code in an else block uses the condition in the if to infer the type of the variable. However if the if contains an early return the rest of the function should be treated as the else of the if from we we returned.

Code

// A self-contained demonstration of the problem follows...
type Foo = { a: string };
function isFoo(x): x is Foo {
    return x && typeof(x.a) === 'string';
}

type Bar = { b: string };

function buz1(arg: Foo|Bar) : string {
    if (isFoo(arg))
        return arg.a;  // OK arg inferred to be Foo
    else
        return arg.b; // OK arg inferred to be Bar
}

function buz2(arg: Foo|Bar) : string {
    if (isFoo(arg)) 
        return arg.a;  // OK arg inferred to be Foo

    return arg.b;  // ** Error b isn't a member of Foo|Bar **
}

Expected behavior:
function buz2 should compile with no error.
Actual behavior:
Error when accessing member b of arg even though arg can be inferred to be of type Bar (as it is in buz1.else).

@DanielRosenwasser
Copy link
Member

Hey @lanzkron I believe this will be fixed in TypeScript 2.0 where we'll start using control flow analysis for types. Give the nightlies a try out with npm install -g typescript@next and see how it works!

@ahejlsberg
Copy link
Member

You can read more about this feature in #8010.

@ahejlsberg ahejlsberg added the Duplicate An existing issue was already created label May 31, 2016
@basarat
Copy link
Contributor

basarat commented May 31, 2016

@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