ERROR | 'string' 형식의 식을 인덱스 형식에 사용할 수 없으므로 요소에 암시적으로 'any' 형식이 있습니다.
type Colors = {
skyblue: string;
lightGreen: string;
green: string;
blue: string;
violet: string;
pink: string;
yellow: string;
orange: string;
peach: string;
};
type MainColor = Pick<Colors, 'skyblue'>;
type SubColors = Omit<Colors, 'skyblue'>;
export const colors: Colors = {
skyblue: 'bg-main-skyblue',
lightGreen: 'bg-sub-lightGreen',
green: 'bg-sub-green',
blue: 'bg-sub-blue',
violet: 'bg-sub-violet',
pink: 'bg-sub-pink',
yellow: 'bg-sub-yellow',
orange: 'bg-sub-orange',
peach: 'bg-sub-peach',
};
위와 같은 코드로 colors 코드를 짜고
const handleClick = (color: string) => {
console.log('키', customColors.main[color]);
}
위의 코드는 빨간 줄이 뜬다. TypeScript가 stirng 타입의 key
사용을 허용하지 않아서 뜨는 에러이다.
더 자세하게 설명하자면 string literal
타입만 허용되는 곳에 string
타입을 사용했기때문이다.
string Vs string literal
string
은 좀더 제너릭하고 특정한 것을 나타내지는 않는다. 예를 들어,
const color = 'skyblue' // 1
let color = 'skyblue' // 2
const color:string = 'skyblue' // 3
여기서 2, 3번은 string 타입이지만 1번은 string literal 타입이다. 그 이유는 2번은 let을 사용했기때문에 string이라면 재할당이 가능하고 3번은 명시적으로 표현을 해주었기 때문이다. 하지만, 1번은 typescript가 자동으로 narrowed type으로 선언해서 template literal로 결정되는 것이다.
String Literal 키를 통한 객체 접근
const handleClick = (color: string) => {
const a = 'skyblue';
console.log('키', customColors.main[a]);
}
위 코드는 제대로 작동한다. 그 이유는 a
가 literal type이기 때문이다. 하지만 string 값으로 들어오는 매개변수인 color를 무조건 사용해야하기에 옳은 해결책은 아니다. 그렇다면 어떻게 할 수 있을까?
Index Signature 선언
type Colors = {
[key: string]: string; // index signature
skyblue: string;
lightGreen: string;
...
};
type MainColor = Pick<Colors, 'skyblue'>;
type SubColors = Omit<Colors, 'skyblue'>;
(...)
위의 저 한줄 코드만 추가해주면 된다. 이렇게 하면 SubColors 타입을 사용하는 객체는 오류가 해결이 된다. 하지만 MainColor는 'skyblue'라는 정확한 값 즉, string literal이기 때문에 여전히 오류가 난다.
Partial 유틸리티 타입
Colors의 모든 필드를 optional한 타입으로 지정해준 것과 같다. 사실 약간의 치트키 느낌이긴 하지만 해결된게 중요한 것 아니겠나 싶다.
type Colors = {
\[key: string\]: string; // index signature
skyblue: string;
lightGreen: string;
...
};
type MainColor = Partial;
type SubColors = Omit<Colors, 'skyblue'>;
(...)
'TypeScript' 카테고리의 다른 글
유틸리티 타입 Pick<T, K> 프젝에 적용하기 | TypeScript (0) | 2024.03.19 |
---|---|
TypeScript, Next.js, React.js 이미지 미리보기 | Image Preview (0) | 2024.03.18 |
제네릭 | 한 입 크기로 잘라먹는 타입스크립트 (1) | 2024.03.12 |
TypeError: Cannot read properties of undefined (reading 'length') 의 원인과 해결 방안 (0) | 2024.03.09 |