簡體   English   中英

如何根據Typescript中的propertyName獲取object的值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM