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

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

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

问题

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

将这段代码:

  1. export type Writable<T> = {
  2. -readonly [K in keyof T]: T[K];
  3. };
  4. class Foo {
  5. readonly foo = 'foo';
  6. }
  7. class Bar {
  8. readonly bar = 'bar';
  9. }
  10. type WritableFooBar = Writable<Foo | Bar>;
  11. declare function isFoo(obj: any): obj is Foo;
  12. function test(foobar: WritableFooBar): void {
  13. if (!isFoo(foobar)) {} // 也会出现在if(isFoo())中
  14. foobar
  15. // ^? Foo | Writable<Bar>
  16. }

翻译为:

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

英文:

Take this code :

  1. export type Writable&lt;T&gt; = {
  2. -readonly [K in keyof T]: T[K];
  3. };
  4. class Foo {
  5. readonly foo = &#39;foo&#39;;
  6. }
  7. class Bar {
  8. readonly bar = &#39;bar&#39;;
  9. }
  10. type WritableFooBar = Writable&lt;Foo | Bar&gt;;
  11. declare function isFoo(obj: any): obj is Foo;
  12. function test(foobar: WritableFooBar): void {
  13. if (!isFoo(foobar)) {} // happens also with if(isFoo())
  14. foobar
  15. // ^? Foo | Writable&lt;Bar&gt;
  16. }

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:

确定