Skip to content

Union with constrained type variable doesn't narrow in negative branch of type predicate #44814

Closed
@saschaB91

Description

@saschaB91

⏯ Playground Link

https://www.typescriptlang.org/play?#code/LAKAxgNghgzjAEAVApjALgYWnAPIgfPAN6jxnxoCeADsgOYCuUATgCYAUAblBAFzwMAdgGtBAewDuggJT9uEeAEsEiYqXIbmyNA2aCKzBsgDc6sgF8z8AGZd+ghgFsARsmaz4nMYtbFLIDQALOyQPLx8-K2shMC4eflUAH3gHFzcw718SAI1yRWt4djRA5QA6KlpGFg55aWk1HNzc4rLg2tNGpvItHT0Orvh-AZaYUtt2q39-UEhYFVRMbBgAJjx4ZAAPNGRBVgQAEShtwmyNCvomNji+ARFxKTCeJRUGgZ7dfTRDE0mokNTXO45JlIp02gkMhEiENyNFBLF5Al4MkAelgVCrBp8oURuUaBdqtc6q8BuRcW0eNJ+qSyO8+pjyDCmrjxpTqRZQOYgA

Issue Type: Bug

This error is only shown when using the TypeScript-Server not when compiling code.
When using an generic class with a method as type guard, it will only be validated correctly if you do not extend the generic type.
The first class is ok but the second shows an error on "this.f(val)" even though nothing changed

class TestClass<T> {
    typeguard(val: unknown): val is T {
        return true;
    }
    f(v: number): void {}
    h(v: T): void {}
    func(val: T | number): void {
        if (this.typeguard(val)) {
            this.h(val);
            return;
        }
        this.f(val);
    }
}
class TestClass2<T extends Date> {
    typeguard(val: unknown): val is T {
        return true;
    }
    f(v: number): void {}
    h(v: T): void {}
    func(val: T | number): void {
        if (this.typeguard(val)) {
            this.h(val);
            return;
        }
        this.f(val);
    }
}

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issueRescheduledThis issue was previously scheduled to an earlier milestone

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions