Microsoft/TypeScript

Strange narrowing when using instanceof on template class with optional field

Open

#49.352 aberto em 2 de jun. de 2022

Ver no GitHub
 (1 comment) (1 reaction) (0 assignees)TypeScript (6.726 forks)batch import
BugDomain: check: Control FlowHelp Wanted

Métricas do repositório

Stars
 (48.455 stars)
Métricas de merge de PR
 (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)

Description

Bug Report

TypeScript narrows type wrong when using instanceof for generic class with optional field

🔎 Search Terms

typescript instanceof template optional narrowing

🕗 Version & Regression Information

It seems the bug present in all versions: old, actual and nightly

⏯ Playground Link

https://www.typescriptlang.org/play?target=8&ts=4.8.0-dev.20220602#code/MYGwhgzhAECiA8sB80DeAoaXoFMD8AXHANzoC+66okMAgvAJIo4AeALjgHYAmMCTGbNABmASxwhuRTgFcAtgCMcAJ2gBeaAAZSFKuCjRaARkbN2XXodNpM2MRO5HC0WYpU7K1A7QBM11hw8dNaCduKSRtLySqoaRh7owjKcwGyiAPacIqYAFGBE9K4xSACUNkKiwtB50KKcEGxgKTjpVcZloUJYYAB09hGkQhQVVTV1DU3ALW0+HbZd0L39joPYFBRAA

💻 Code

class E<E> {
    e?: E;
}

class A<I> extends E<I>{
    field: number = 0;
}

class A1<I> extends A<I> {
    field1?: number;
}

class A2<I> extends A<I> {
    field1: number = 1;
}

function f<I>(a: A<number>) {
    if (a instanceof A1) {
        a.field1;
    }
    if (a instanceof A2) {
        a.field1;
    }
}

🙁 Actual behavior

Property 'field1' does not exists in type A in first if, variable a narrowed to A

🙂 Expected behavior

variable a narrowed to A1 in first if and property field1 exists

Guia do colaborador