Skip to content

Broken type inference with a typeguard in a if statementΒ #53216

Closed
@JeanMeche

Description

@JeanMeche

Bug Report

πŸ”Ž Search Terms

  • type guard
  • inference
  • if condition

πŸ•— Version & Regression Information

This is a regression.

Inference was OK on 4.7.4 but broken on 4.8.4 and 4.9.5 (tested on the playground).

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

export type Writable<T> = {
    -readonly [K in keyof T]: T[K];
};

class Foo {
    readonly foo = 'foo';
}

class Bar {
    readonly bar = 'bar';
}

type WritableFooBar = Writable<Foo | Bar>;

declare function isFoo(obj: any): obj is Foo;

function test(foobar: WritableFooBar): void {
    if (!isFoo(foobar)) {} // happens also with if(isFoo())

    foobar
    // ^? Foo | Writable<Bar>
}

πŸ™ Actual behavior

foobar is inference as Foo | Writable<Bar>

πŸ™‚ Expected behavior

foobar should be inferred as Writable<Foo|Bar> or WritableFooBar

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions