TypeScript React UseContext初始化报错:默认值类型不兼容
解决React+TypeScript购物车Context初始化类型错误问题
错误信息
Error: Argument of type '{ cartitem: { id: number; name: string; description: string; price: string; }; addCart: () => void; removeCart: () => void; }' is not assignable to parameter of type 'CartContextType'. Types of property 'cartitem' are incompatible. Type '{ id: number; name: string; description: string; price: string; }' is missing the following properties from type 'ICart[]': length, pop, push, concat, and 29 more.ts(2345)
问题代码
import React, { createContext } from 'react'; export interface ICart { id: number; name: string; description: string; price: string; } export type CartContextType = { cartitem: ICart[]; addCart: (cart: ICart, totalAmount:number) => void; removeCart: (id: number) => void; }; const defalutCart={cartitem:{ id: 0, name: 'string', description: 'string', price: 'string'}, addCart: () => {}, removeCart: () => { } } export const CartContext = createContext<CartContextType | null>(defalutCart);
修复方案
调整默认值的类型匹配,确保cartitem为数组,同时让函数参数符合类型定义:
import React, { createContext } from 'react'; export interface ICart { id: number; name: string; description: string; price: string; } export type CartContextType = { cartitem: ICart[]; addCart: (cart: ICart, totalAmount:number) => void; removeCart: (id: number) => void; }; // 修正默认值:cartitem改为空数组,函数参数匹配类型定义 const defalutCart = { cartitem: [] as ICart[], addCart: (_cart: ICart, _totalAmount: number) => {}, removeCart: (_id: number) => { } } // 无需保留| null,默认值已完全符合CartContextType export const CartContext = createContext<CartContextType>(defalutCart);
错误原因说明
- 类型定义中
cartitem是ICart[]数组类型,但你初始化的默认值是单个ICart对象,类型不匹配导致TS报错。 - 定义的
addCart和removeCart有明确参数要求,默认空函数最好声明对应参数,避免后续使用时出现类型偏差。 - 提供完全符合类型的默认值后,
createContext的泛型可以去掉| null,后续使用useContext时无需额外判断空值。
内容的提问来源于stack exchange,提问作者BenZard
相关产品推荐
相关产品推荐

