英文:
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<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>
}
Is type inference broken in this case or am I missing something ?
答案1
得分: 0
这实际上是一个在4.8版本中出现的回归问题,在5.0版本中已修复。
英文:
This actually a regression that appeared in 4.8 and was fixed in 5.0.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论