![](/img/trans.png)
[英]How to get the value from DB based on the user input using Typescript
[英]How to get value from object based on propertyName in Typescript?
我可以撥打 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}
/>
但是 Typescript 給我錯誤消息Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
row.order_status
被輸入為一個字符串。 雖然chipColors
只接受delivered | pending | canceled
delivered | pending | canceled
delivered | pending | canceled
。 所以,要么你輸入不同的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.