TypeScript报错any无法赋值给never useState状态类型定义问题
问题根因
初始化useState时传入的attributes初始值是空数组[],TypeScript没有可参考的数组元素类型,会默认将其推断为never[]类型——也就是该数组不允许存入任何类型的值,因此在执行[...attributes, value]的展开新增操作时,会抛出「Type any is not assignable to type never」的类型错误。
另外代码里的事件参数e没有声明类型,在TS严格模式下会被判定为隐式any,也会触发额外的类型提示。
修复方案
调用useState时显式传入泛型参数,明确状态的完整类型结构,同时给事件对象补充对应类型即可:
import { useState, ChangeEvent } from 'react' // 定义表格状态的类型结构 type TableAttributesState = { attributes: string[] // 明确attributes是字符串类型的数组,替代默认的never[] } const [tableAttributes, setTableAttributes] = useState<TableAttributesState>({ attributes: [], }) // 给复选框change事件补充对应DOM类型,消除隐式any报错 const handleChange = (e: ChangeEvent<HTMLInputElement>) => { const { value, checked } = e.target const { attributes } = tableAttributes console.log(`${value} is ${checked}`) // 勾选时追加值的逻辑不会再报类型错误 if (checked) { setTableAttributes({ attributes: [...attributes, value], }) } // 取消勾选的逻辑可自行补充,例如过滤掉当前取消选中的value即可 }
补充说明
- 如果业务中复选框的
value不是字符串(比如是数字类型),只需要把string[]替换为number[],和实际业务类型对齐即可 - 凡是初始值为空数组的状态,不要依赖TS自动推断类型,必须显式声明数组的元素类型,否则都会被推断为
never[]引发同类报错 - React表单事件需要引入对应类型泛型,传入操作的DOM元素类型(复选框、输入框都对应
HTMLInputElement),即可获得完整的target属性类型提示。
内容的提问来源于stack exchange,提问作者blackrox
相关产品推荐
相关产品推荐

