Marais.lee
Welcome to Marais's IT Home
Marais.lee
전체 방문자
오늘
어제
  • 분류 전체보기 (87)
    • co-task 프로젝트 (7)
    • Study (28)
      • 자바스크립트 (5)
      • 모던 리액트 Deep Dive (7)
      • 용어 (1)
      • 컴퓨터과학 (2)
      • 코테 (12)
      • 네트워크 (0)
    • 개발 환경 (3)
    • Next.js (pages router) (9)
    • Next.js (app router + 14v) (4)
    • TypeScript (11)
    • 라이브러리 (8)
    • 후기 및 고민 (10)
    • 맥북관련 셋팅 및 오류 (4)
    • Obsidian | 옵시디언 (1)
반응형

인기 글

최근 글

블로그 메뉴

  • 홈
  • 태그
  • 방명록
250x250
hELLO · Designed By 정상우.
Marais.lee

Welcome to Marais's IT Home

TypeScript

ERROR | 'string' 형식의 식을 인덱스 형식에 사용할 수 없으므로 요소에 암시적으로 'any' 형식이 있습니다.

2024. 6. 14. 23:56
728x90

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'>;

(...)
728x90
반응형
저작자표시 비영리 변경금지 (새창열림)

'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
    'TypeScript' 카테고리의 다른 글
    • 유틸리티 타입 Pick<T, K> 프젝에 적용하기 | TypeScript
    • TypeScript, Next.js, React.js 이미지 미리보기 | Image Preview
    • 제네릭 | 한 입 크기로 잘라먹는 타입스크립트
    • TypeError: Cannot read properties of undefined (reading 'length') 의 원인과 해결 방안
    Marais.lee
    Marais.lee
    구글링으로 한국어로 된 글을 찾지 못했거나 이해하는데 어려움이 있었던 이슈를 공유합니다.

    티스토리툴바