React+TypeScript项目定义值时报ts(2345)类型不匹配错误如何解决?
报错根因
Argument of type '{}' is not assignable to parameter of type 'SetStateAction<boolean[]>'. Type '{}' is not assignable to type '(prevState: boolean[]) => boolean[]'.
Type '{}' provides no match for the signature '(prevState: boolean[]): boolean[]'.ts(2345)
报错核心是状态类型不匹配:你调用useState([true])初始化时,TS会自动推导addButtonFruits的类型为boolean[](布尔数组),但你在useEffect中尝试给这个状态赋值对象类型的initialAddButtonFruits,触发了类型校验报错。
解决方案
根据实际业务需求选择对应改法即可:
方案1:状态需要是「水果名作为key、布尔值作为value」的对象
修改useState的类型定义,明确指定状态为对象类型:
// 定义状态类型:key为水果名字符串,value为布尔值 type AddButtonFruits = Record<string, boolean> // 给useState加泛型指定类型,初始值设为空对象 const [addButtonFruits, setAddButtonFruits] = useState<AddButtonFruits>({}) useEffect(() => { const initialAddButtonFruits = {} as AddButtonFruits; // 遍历赋值用forEach更合适,map多用于生成新数组 fruitsArray.forEach((each) => (initialAddButtonFruits[each] = true)); setAddButtonFruits(initialAddButtonFruits); }, []);
方案2:状态确实需要是布尔数组
修改useEffect里的生成逻辑,输出数组而非对象:
const [addButtonFruits, setAddButtonFruits] = useState([true]); useEffect(() => { // 生成和fruitsArray长度一致、每一项都是true的布尔数组 const initialAddButtonFruits = fruitsArray.map(() => true); setAddButtonFruits(initialAddButtonFruits); }, []);
内容的提问来源于stack exchange,提问作者Nhan Nguyen
相关产品推荐
相关产品推荐

