Sabyasachi Rout
Sabyasachi Rout

Reputation: 1

How to get a type as an element of array?

const ratingList = {1: "", 2: "", 3: "", 4: "", 5: ""}

type ratingType = keyof typeof ratingList

......

{Object.keys(ratingList).map((row, index) => {
   if (parseInt(row) <= rating)
       return <div key={index}><TiStar size={22} /></div>
   else
       return <div key={index}><TiStarOutline size={20} /></div>
 })}

Want to define a type that reads the rating list. basically i want to have an array [1, 2, 3, 4, 5] as ratingList so that i could use it somewhere else. And the type should be only the element of that array. If I want to update rating list, this work around is ugly as hell. Can anyone suggest me to do in a better way!!!!

Upvotes: 0

Views: 44

Answers (1)

JeromeBu
JeromeBu

Reputation: 1159

There is a way to do what you want if I understand correctly what you ask :

const ratingList = [1, 2, 3] as const 
// would also works with string ["a", "b"] as const

type RatingListMember = typeof ratingList[number] // -> is of type : 1 | 2 | 3
// with string would be of type : "a" | "b"

Upvotes: 1

Related Questions