首页 > 解决方案 > 收到错误:键入'[null,Dispatch>]' 不能分配给打字稿反应

问题描述

我正在从事打字稿项目,我想要useState功能setInterval,但我遇到错误,我正在使用useState这样的语句,谁能帮我解决这个问题?任何帮助将不胜感激。

const [intervalData, setIntervalData] : [null | NodeJS.Timeout, (interval: null | NodeJS.Timeout) => void] = useState(null); 

错误 :

Type '[null, Dispatch<SetStateAction<null>>]' is not assignable to type '[Timeout | null, (interval: Timeout | null) => void]'.
  Type 'Dispatch<SetStateAction<null>>' is not assignable to type '(interval: Timeout | null) => void'.
    Types of parameters 'value' and 'interval' are incompatible.
      Type 'Timeout | null' is not assignable to type 'SetStateAction<null>'.
        Type 'Timeout' is not assignable to type 'SetStateAction<null>'.
          Type 'Timeout' provides no match for the signature '(prevState: null): null'.ts(2322)

标签: reactjstypescript

解决方案


如果不指定类型参数,useState则状态的类型将从传递给的值中推断出来useState。由于您传入null,状态的类型将为null,这意味着它除了 之外没有其他值null

您可以为状态指定更广泛的类型作为类型参数:

const [intervalData, setIntervalData]:[null | NodeJS.Timeout, (interval: null | NodeJS.Timeout) => void] = useState<null | NodeJS.Timeout>(null);

游乐场链接

注意:我会完全删除类型注释const,但我猜这可能只是为了问题中的示例而添加的。


推荐阅读