类型推断在使用类型守卫时是否失效, if 语句中使用?

huangapple go评论65阅读模式
英文:

Is type inference broken when a type guard is used in a if statement

问题

这段代码存在类型推断问题,还是我漏掉了什么?

将这段代码:

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)) {} // 也会出现在if(isFoo())中

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

翻译为:

这段代码存在类型推断问题,还是我漏掉了什么?

英文:

Take this code :

export type Writable&lt;T&gt; = {
    -readonly [K in keyof T]: T[K];
};

class Foo {
    readonly foo = &#39;foo&#39;;
}

class Bar {
    readonly bar = &#39;bar&#39;;
}

type WritableFooBar = Writable&lt;Foo | Bar&gt;;

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

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

    foobar
    // ^? Foo | Writable&lt;Bar&gt;
}

Is type inference broken in this case or am I missing something ?

Playground

答案1

得分: 0

这实际上是一个在4.8版本中出现的回归问题,在5.0版本中已修复。

英文:

This actually a regression that appeared in 4.8 and was fixed in 5.0.

huangapple
  • 本文由 发表于 2023年3月12日 19:39:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定