[英]How to type a nested object?
I want to type an object to include it in a React state.我想输入 object 以将其包含在 React state 中。 This is a shopping cart object with a couple of product IDs and their props.
这是一个购物车 object,带有几个产品 ID 及其道具。
Object: 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.等等,其中产品 ID 可以是任何相同格式的字符串。
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
.现在,当您像您提到的那样使用它时,
cart
将是CartInterface
类型。 If this answers your question, I suggest some deeper reading of the typescript documentation .如果这回答了您的问题,我建议您更深入地阅读typescript 文档。 You can check this playground link to see it in action.
您可以查看此游乐场链接以查看它的实际效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.