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

给定下面的代码:

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

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

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


当前回答

如果您以这种方式使用UseState,应该不会有问题

const [data, setData] = useState<any>([]);

在Javascript的情况下,它直接工作,因为所有的数据类型都是Any 默认情况下,Typescript中不是这样的,所以你必须让语言知道:)

其他回答

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

例子:

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

我有同样的错误,把点符号换成了括号符号来抑制它。

例如:

obj.name -> obj['name']

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

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

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

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

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

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

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