如何为React状态中的嵌套购物车对象定义TypeScript类型?
在React TypeScript中定义购物车State的类型
你可以通过TypeScript接口/类型别名来定义这个购物车结构,分两步实现:
1. 定义单个购物项的类型
先为购物车中的单个商品对象定义类型,覆盖name、price、quantity、subtotal这些属性:
// 用接口定义 interface CartItem { name: string; price: number; quantity: number; subtotal: number; } // 或者用类型别名,效果一致 type CartItem = { name: string; price: number; quantity: number; subtotal: number; };
2. 定义整个购物车的类型
购物车是一个以任意字符串格式的产品ID为键、对应值为上述CartItem的对象,有两种常用定义方式:
方式一:使用Record工具类型
type CartInterface = Record<string, CartItem>; // 或者用接口继承的写法 interface CartInterface extends Record<string, CartItem> {}
方式二:使用索引签名
interface CartInterface { [productId: string]: CartItem; }
3. 在useState中使用该类型
现在就可以按你期望的方式在React的useState中引用这个类型,同时可定义初始购物车状态:
import { useState } from 'react'; // 初始购物车状态示例 const CartState: CartInterface = { "1047151242": { "name": "Item 1 name", "price": 22.99, "quantity": 2, "subtotal": 45.98 }, "3327300382": { "name": "Item 2 name", "price": 90.49, "quantity": 2, "subtotal": 180.98 } }; const [cart, setCart] = useState<CartInterface>(CartState);
这样就能给购物车State提供完整的TypeScript类型校验,避免类型错误。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

