简体   繁体   中英

How to get value from object based on propertyName in Typescript?

I can do this in 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

row.order_status is typed as a string. While chipColors only accepts a key that is of the type 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:

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 ... />

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM