TypeScript
Record Type
단점이없어지고싶은개발자
2022. 7. 16. 16:15
반응형
Record Type이란?
Record Type은 Record <Key, Type> 형식으로 키가 Key이고 값이 Type인 객체 타입이다.
Record Type 과 Index Signature
TypeScript에서 인덱스 시그니처(Index Signature)는 대괄호로 객체에 접근하는 방법이다.
Index Signature 방식
type foo = {
[name: string]: number
};
let user:foo = {
'a': 1,
'b': 2,
'c': 3,
};
Record Type 방식
type foo = Record<string, number>
let user:foo = {
'a': 1,
'b': 2,
'c': 3,
};
두 가지 방식은 둘 다 비슷 해보이지만, 구문 관점에서는 Index Signature가 더 좋아보인다. name과 Key의 의도를 확연히 확인 할 수 있기 때문이다.
Index Signature의 단점
문자열 리터럴을 Key로 사용하는 경우 오류가 발생한다
만약 Record Type으로 작성한다면?
아래를 보면, 문자열 리터럴을 사용하여 Key에 허용 가능한 값을 제한한다
또한 Keyof와 Record Type을 아래와 같이 사용한다
type key = {
a: string;
b: number;
c: string;
};
type keyType = Record<keyof key, string>;
let user:keyType = {
a: 'string',
b: '20',
c: 'string'
}
반응형