这类似于#40796374,但这是围绕类型,而我使用接口。

给定下面的代码:

接口Foo { 名称:字符串; } 函数go() { 让实例:Foo | null = null; Let mutator = () => { 实例= { 名称:“字符串” }; }; mutator (); If (instance == null) { console.log('实例为空或未定义'); }其他{ console.log (instance.name); } }

我有一个错误说'属性'名称'不存在类型'从不'。

我不明白实例怎么会是一个“永远”。有人能解释一下吗?


当前回答

在我的例子中,发生这种情况是因为我没有输入变量。

所以我创建了搜索界面

export interface Search {
  term: string;
  ...
}

我改变了

searchList = [];

为此,它起作用了

searchList: Search[];

其他回答

因为你把instance赋值为null。编译器推断它只能是null。所以它假设else块永远不会被执行,所以instance的类型永远不会在else块中。

现在,如果你不将它声明为字面值null,而是通过任何其他方式获取它(例如:let instance: Foo | null = getFoo();),你会看到实例在if块中为空,而Foo在else块中为空。

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

编辑:

更新示例中的问题实际上是编译器的一个开放问题。 看到的:

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

我有什么问题吗?和!

这件作品对我很有用。

if (ref != null){
    if (ref.current != null)
        ref.current.appendChild(child);
}

有时,初始值可能为空。 在这种情况下,你可能会说例子

让val = data。notificationId——>这里它会抛出一个错误。 所以我们可以简单地写出来 let val = data && data. notificationid

对于typescript开发者… 如果你使用React.useRef()钩子 声明并使用变量类型any,而不是预先分配null。

例子:

const initialRef: any = null;
const ref = React.useRef(initialRef);

这似乎类似于这个问题:当使用strictNullChecks在回调中更改值时,False“属性不存在于类型'never'”,这是这个问题(讨论)的副本:控制流分析中的权衡。

这个讨论很长,如果你找不到好的解决方案,你可以试试这个:

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