[typescript] key-value 쌍 자료구조(Map) 타입 지정하기

리오·2023년 7월 22일
post-thumbnail

맵(Map)이란?

Map은 Key를 이용하여 Value(데이터)를 저장하고 검색하는 방식의 자료구조입니다.
Key는 중복될 수 없고, 삽입, 삭제, 검색 연산이 가능합니다.

객체(Object)를 이용하는 경우

자바스크립트의 객체(Object)는 내부적으로 해시테이블(Hash Table) 구조로 되어있기 때문에, 맵(Map)처럼 사용할 수 있습니다.

저의 경우, 곤충의 성장 단계를 8단계로 나누어, 각 단계별로 LED에 표시되는 색상을 저장하는 자료구조가 필요했습니다. 그래서 다음과 같이 코드를 작성하였습니다.

const colorsByLevel = {
	1: '#FFFFFF',
	2: '#FF0000',
	3: '#00FF00',
	4: '#0000FF',
	5: '#FF00FF',
	6: '#00FFFF',
	7: '#FFFF00',
	8: '#909090',
};

하지만 이렇게 작성하고보니, 다음과 같은 함수를 사용할 때, 에러가 발생하였습니다.

type Level = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
type HexColor = `#${string}`;

const colorsByLevel= {
	1: '#FFFFFF',
	2: '#FF0000',
	3: '#00FF00',
	4: '#0000FF',
	5: '#FF00FF',
	6: '#00FFFF',
	7: '#FFFF00',
	8: '#909090',
};



const getColor = (level: Level): HexColor => {
	return colorsByLevel[level];
  //에러: 'string' 형식은 '`#${string}`' 형식에 할당할 수 없습니다.ts(2322)

};

const currentLevel: Level = 4;
console.log(colorsByLevel[currentLevel]);

따라서 colorsByLevel의 타입을 좀 더 명확히 지정해 줄 필요가 있었습니다. 이렇게 객체에서 사용되는 key와 value의 타입을 지정해주고 싶다면 다음과 같은 방법을 사용합니다.

type Level = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
type HexColor = `#${string}`;

//타입 지정: { [key in Level]: HexColor }
const colorsByLevel: { [key in Level]: HexColor } = {
	1: '#FFFFFF',
	2: '#FF0000',
	3: '#00FF00',
	4: '#0000FF',
	5: '#FF00FF',
	6: '#00FFFF',
	7: '#FFFF00',
	8: '#909090',
};

const getColor = (level: Level): HexColor => {
	return colorsByLevel[level];
};

const currentLevel: Level = 4;
console.log(colorsByLevel[currentLevel]); //#0000FF

Map 객체 사용

ECMAScript 6부터 key에 대한 value를 매핑하기 위한 새로운 데이터 구조가 도입되었는데, 그 중 하나가 바로 Map객체입니다.

이 Map을 사용하고 싶다면 다음과 같이 코드를 수정할 수 있습니다.

type Level = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
type HexColor = `#${string}`;

const color: HexColor = '#123455';

const colorsByLevel: Map<Level, HexColor> = new Map([
	[1, '#FFFFFF'],
	[2, '#FF0000'],
	[3, '#00FF00'],
	[4, '#0000FF'],
	[5, '#FF00FF'],
	[6, '#00FFFF'],
	[7, '#FFFF00'],
	[8, '#909090'],
]);

const getColor = (level: Level): HexColor | undefined => {
	return colorsByLevel.get(level);
};
profile
오늘도 승승장구를 위해 연습 중

0개의 댓글