microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.7k stars 12.45k forks source link

improper declared type cause narrow type not work when its computed type is not union. #39114

Open ShuiRuTian opened 4 years ago

ShuiRuTian commented 4 years ago

TypeScript Version: 4.0

Search Terms:

Code

interface A {
    type:'A'
}

interface B {
    type:'B'
}

function assert(x:any) :asserts x is A|B{

}

function foo(x: any): any {
    x;  // any
    assert(x);
    x;  // A | B
    if (x.type === 'A') {
        return x;
    }
    x;  // B
    if (x.type === 'B') {
        return x;
    }
    x;  // B, but should be never.
//  ^?
}

Expected behavior: the last x should be never.

Actual behavior: still B.

Playground Link: https://www.typescriptlang.org/play/index.html?ts=4.0.0-dev.20200615&ssl=1&ssc=1&pln=25&pc=2#code/JYOwLgpgTgZghgYwgAgIIG8BQyfLATwAcIAuAclTMwF9NNRJZEUAhLXPI0slq2zGAFcQCMMAD2IZHADOM6GAAUADxJwQ+AJTI1chTOTLkwA6gA+bOvyEixk5DHHiVJaRs2v1+ZO1zKA3DgA9EFu+Ni4svJQSsqa-hE4AcGhqMhmyCyJxjDIKgB0BMTIALxlyBRk2r4cOFAQYIJQUgHZtBzJyCGZ2cC5BUUoZSUVvNXZHPWNzYYJHO1+gV2hWdRAA

Related Issues:

ShuiRuTian commented 4 years ago

The reason is isMatchingReferenceDiscriminant function return false at the second time. Declared type is no use here.

38839 Add this link, for I meet similar problem in the fix.

orta commented 4 years ago

( I sneakily edited the issue body to be a twoslash compiler repro to test the bot )

orta commented 4 years ago

@typescript-bot run repros

typescript-bot commented 4 years ago

Heya @orta, I've started to run the code sample repros for you. Here's the link to my best guess at the log.

orta commented 4 years ago

Think I've got the bugs down, @typescript-bot run repros

typescript-bot commented 4 years ago

Heya @orta, I've started to run the code sample repros for you. Here's the link to my best guess at the log.

typescript-bot commented 2 years ago

:wave: Hi, I'm the Repro bot. I can help narrow down and track compiler bugs across releases! This comment reflects the current state of the repro in the issue body running against the nightly TypeScript.


Issue body code block by @ShuiRuTian

:warning: Assertions:

Historical Information
Version Reproduction Outputs
4.2.2, 4.3.2, 4.4.2, 4.5.2, 4.6.2

:warning: Assertions:

  • (parameter) x: B