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

给定下面的代码:

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

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

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


当前回答

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

这样写会很有帮助:

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

其他回答

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

所以我创建了搜索界面

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

我改变了

searchList = [];

为此,它起作用了

searchList: Search[];

在useState中,如果你从未声明过类型:

它假设它的类型是never,所以它显示这个错误:"属性不存在类型'never'"

你可以这样输入:

const [datalist, setDataList] = useState<Array<Object>>([]);

如果你在参数中收到错误,那么保持任何或任何[]类型的输入,如下所示

getOptionLabel={(option: any) => option!.name}
 <Autocomplete
    options={tests}
    getOptionLabel={(option: any) => option!.name}
    ....
  />

因为你把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

对我来说,以下代码是工作的:

const [disc, setDisc] = useState<any[]>([]);

到目前为止,我所看到的是:当你没有指定传递给useState()的类型时,它推断它永远是类型。 通过使用any[],您可以在请求时传递数据。