reactjs - 收到错误:键入'[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)
解决方案
如果不指定类型参数,useState
则状态的类型将从传递给的值中推断出来useState
。由于您传入null
,状态的类型将为null
,这意味着它除了 之外没有其他值null
。
您可以为状态指定更广泛的类型作为类型参数:
const [intervalData, setIntervalData]:[null | NodeJS.Timeout, (interval: null | NodeJS.Timeout) => void] = useState<null | NodeJS.Timeout>(null);
注意:我会完全删除类型注释const
,但我猜这可能只是为了问题中的示例而添加的。
推荐阅读
- javascript - 如何用 String.prototype 编写我自己的方法?
- java - Java 等价于 php chr() 函数
- c - void 函数调用作为表达式
- google-apps-script - 如何自动更新单元格值?
- javascript - 基于下拉选择在客户端使用 EJS 过滤猫鼬数据
- linux - 用于查找 cmd 的正则表达式以输出所有带有“e”的文件,但不在名称的开头/结尾
- ios - 目标 C:Safari 中的“打开方式”对话框应将我的应用程序显示为选项
- apache-camel - Apache camel 的 google sheet 组件中是否有 ValueInputOption 参数支持?
- c# - Properties.Settings.Default.myList.Add(item) 不添加我的项目
- java - 与 sharedpreference 共享一个 int 变量