FE
Typescript : 객체 내 특정 string인 key값에 해당하는 value 가져오기
히치키치
2022. 7. 4. 21:15
[JS version]
- 상수값을 관리하는 constant 폴더 내 Flexitarian, Pollo, Pesco, Lacto Ovo, Lacto, Vegan, NonVegan에 각각 지정된 색상 값이 있음
- api response로 Flexitarian, Pollo, Pesco, Lacto Ovo, Lacto, Vegan, NonVegan 중 1개가 전달됨
- 전달받은 것에 대응하는 색상을 화면에 랜더링하면 됨
- Lacto Ovo는 띄어쓰기가 있기 때문에 직접 ""로 묶어줘야 함
export const state = {
Flexitarian: `${theme.light.mint}`,
Pollo: `${theme.light.yellow}`,
Pesco: `${theme.light.gray}`,
"Lacto Ovo": `${theme.light.pinkLight}`,
Lacto: `${theme.light.greenLight}`,
Vegan: `${theme.light.pinkDark}`,
NonVegan: `${theme.light.greenSub}`,
};
문제점
- 다음과 같이
color
속성을 지정하려고 했으나... 객체의 key는 기본적으로 number인데 어캐 string이냐며 typescript가 에러처리를 뱉어냈따....
<Step color={state[d.level]} />
해결방법
- 결국 state 객체 변수에 이 변수는 typescript에서 디폴트로 지정된 객체가 아니라 아주 친절하게 직접... key는 string이고 value는 any인 객체라고 명시했다..
export const state: { [index: string]: any } = { Flexitarian: `${theme.light.mint}`, Pollo: `${theme.light.yellow}`, Pesco: `${theme.light.gray}`, "Lacto Ovo": `${theme.light.pinkLight}`, Lacto: `${theme.light.greenLight}`, Vegan: `${theme.light.pinkDark}`, NonVegan: `${theme.light.greenSub}`, };