'属性不存在于类型'从不' [英] 'Property does not exist on type 'never'

查看:34
本文介绍了'属性不存在于类型'从不'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这类似于 #40796374,但那是围绕类型,而我正在使用接口.

This is similar to #40796374 but that is around types, while I am using interfaces.

给定以下代码:

interface Foo {
  name: string;
}

function go() {
  let instance: Foo | null = null;
  let mutator = () => {
   instance = {
     name: 'string'
   };  
  };

  mutator();

  if (instance == null) {
   console.log('Instance is null or undefined');
  } else {
   console.log(instance.name);
  }
}

我有一个错误提示属性 'name' 在类型 'never' 上不存在.

I have an error saying 'Property 'name' does not exist on type 'never'.

我不明白实例怎么可能是从不".任何人都可以对此有所了解吗?

I don't understand how instance could ever be a 'never'. Can anyone shed some light on this?

提前致谢.

推荐答案

因为您将 instance 分配给 null.编译器推断它永远不会是 null 以外的任何东西.所以它假设 else 块不应该被执行,所以 instance 在 else 块中被输入为 never.

Because you are assigning instance to null. The compiler infers that it can never be anything other than null. So it assumes that the else block should never be executed so instance is typed as never in the else block.

现在,如果您不将其声明为文字值 null,而是通过任何其他方式获取它(例如:let instance: Foo | null = getFoo();),您将看到 instance 在 if 块内为 null,在 else 块内为 Foo.

Now if you don't declare it as the literal value null, and get it by any other means (ex: let instance: Foo | null = getFoo();), you will see that instance will be null inside the if block and Foo inside the else block.

从不输入文档:https://www.typescriptlang.org/docs/handbook/basic-types.html#never

更新示例中的问题实际上是编译器的未解决问题.见:

The issue in the updated example is actually an open issue with the compiler. See:

https://github.com/Microsoft/TypeScript/issues/11498https://github.com/Microsoft/TypeScript/issues/12176

这篇关于'属性不存在于类型'从不'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆