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

给定下面的代码:

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

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

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


当前回答

我用下面的表达方式遇到了这个问题:

Const node = item ?<a href={item.link}>{item.name}</a>: item.name

else部分item。name表示属性" name "在类型" never "上不存在。

这是因为如果item对象中什么都没有,那么name属性也不可能存在。

所以当你声明一些基本不可能的事情时,这个警告就会发生(这就是为什么它从来没有)

其他回答

对于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
}

在你的组件中。Ts文件只是像下面那样声明数组

public arrayName = ([] as any[]);

它和我一起为Angular工作过

当我忘记为变量定义类型时,就发生了这种情况。

如果你把Component写成React。FC,使用useState(),

这样写会很有帮助:

const [arr, setArr] = useState<any[]>([])