I want to type an object to include it in a React state. This is a shopping cart object with a couple of product IDs and their props.
Object:
{
"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
}
}
etc. where the product ID can be any string of the same format.
And then reference the type as such:
const [cart, setCart] = useState<CartInterface>(CartState);
If I understand correctly, you just need a type
type CartInterface = {
[s: string]: {
name: string;
price: number;
quantity: number;
subtotal: number;
}
}
Now when you use it like you mentioned, cart
will be of type CartInterface
. If this answers your question, I suggest some deeper reading of the typescript documentation . You can check this playground link to see it in action.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.