Skip to content

Missing narrowing of intersections involving type parameter and primitive typesΒ #43130

Closed
@ahejlsberg

Description

@ahejlsberg

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried.

⏯ Playground Link

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMAjAHgCoD4AUAPALkQ0QDJEBnKAJxjAHNEAfYsxcAEwFNg6uOAlIgDeAWABQiKYhjBE+IWMnSVeANxSA9JsQBlABZwQAGw6IwAQ2rU4Ad0RQ4rclVoMJKgL4Tv4iaEhYBGQAJkxcQmdKGjpGFhJyTh4+QREPaVl5PEQAQgBePPYwbl4wfkV0lSl1LR0DI1NzKxt7RyjXWMrEXxUuYwouNOUqxBrEbT1DEzNLazsHJwSikpSu319-cGh4JGAAZnD8IiWOhmYosBAAWwAjLmoK4Zk5HCgATwAHLjg5bILCgBEp3oAMeI2qGnGdSmjVmLQW7Ri7iePWkfQGQ3Bo0hE3q0yac1aizYl1u9zWPgkm0CO2QABZDpElihzksQmDpBRbDAoBB9FkOSMIBYMSgiDUbtQuBYANY4nTMroqYUYkLijSS6Vy2pREJK6QlCwmKDqnV42HNeZtMoAN3JKMpfnEAW2wWAAFZMIguHgoFxihRom44uZrndqBFjiSw-dBYgIAgqA4WYU-gVEAD9H1jHAAfLJg0zHdEBYkPcbNRHUA

πŸ’» Code

function f1<T>(x: T & string | T & undefined) {
    if (x) {
        x;  // Should narrow to T & string
    }
}

function f2<T>(x: T & string | T & undefined) {
    if (x !== undefined) {
        x;  // Should narrow to T & string
    }
    else {
        x;  // Should narrow to T & undefined
    }
}

function f3<T>(x: T & string | T & number) {
    if (typeof x === "string") {
        x;  // Should narrow to T & string
    }
    else {
        x;  // Should narrow to T & number
    }
}

function f4<T>(x: T & 1 | T & 2) {
    switch (x) {
        case 1: x; break;  // T & 1
        case 2: x; break;  // T & 2
        default: x;  // Should narrow to never
    }
}

function f5<T extends string | number>(x: T & number) {
    const t1 = x === "hello";  // Should be an error
}

πŸ™ Actual behavior

No narrowing or errors where expected.

πŸ™‚ Expected behavior

Narrowing and errors as indicated above.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions