[英]How to get value from object based on propertyName in Typescript?
I can do this in javascript我可以拨打 javascript
const chipColors = {
delivered: "success",
pending: "warning",
canceled: "danger"
}
<Chip
color={chipColors[row.order_status]} <-- Typescript will throw error on this line
text={row.order_status}
/>
But Typescript is giving me error message Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
但是 Typescript 给我错误消息
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
row.order_status
is typed as a string. row.order_status
被输入为一个字符串。 While chipColors
only accepts a key that is of the type delivered | pending | canceled
虽然
chipColors
只接受delivered | pending | canceled
delivered | pending | canceled
delivered | pending | canceled
. delivered | pending | canceled
。 So, either you type row.order_status
differently, or, you can do a type guard, to check if order status is a chipColors
key, like so:所以,要么你输入不同的
row.order_status
,要么你可以做一个类型保护,来检查订单状态是否是一个chipColors
键,像这样:
const chipColors = {
delivered: "success",
pending: "warning",
canceled: "danger",
};
const key = "delivered";
function isChipColor(key: string): key is keyof typeof chipColors {
return Object.keys(chipColors).includes(key);
}
if (!isChipColor(key)) {
return null
}
return <Chip ... />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.