Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- PRISMA
- ps
- nodejs
- js
- GAN
- CV
- frontend
- postgresql
- ML
- python
- CSS
- API
- figma
- react
- Express
- vscode
- PyTorch
- review
- Linux
- ts
- mongo
- html
- C++
- DM
- sqlite
- Three
- DB
- UI
- SOLID
- Git
Archives
- Today
- Total
아카이브
[TS] Type | 03. Record 본문
Record 타입은 제네릭 타입으로, dictionary나 map과 같이 key와 value에 해당하는 값을 받습니다.
type typeRecord = Record<key, value>
Record는 다음과 같이 각각의 요소에 대한 세부사항을 작성하는데 사용됩니다.
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
// Record
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
const borisCatInfo = cats.boris; // CatInfo
Record와 같은 방식으로 작동하는 타입 및 구조는 index signature, map, interface 등이 있습니다.
Record와 이들 타입의 사용법은 비슷하지만, 용도에 따른 차이가 존재합니다.
Index signature
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
// Index signature
const catsIndex: {[name: CatName]: CatInfo} = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
Index는 문자열 리터럴 타입을 Key로 사용할 때 오류가 발생하지만, Record는 리터럴을 허용합니다.
Record는 이를 이용해 Key로 가능한 값을 제한할 수 있습니다.
Interface
interface CatNameInfo {
miffy: CatInfo,
boris: CatInfo,
mordred: CatInfo,
}
type CatName = "miffy" | "boris" | "mordred" | "neo"; // neo가 추가됨
// interface
const catsInterface: CatNameInfo = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
}
interface의 경우 타입 구성값에 변화가 있을 때 빠르게 수정하기가 어렵습니다.
예시와 같이 CatName에 "neo" 리터럴이 추가되었다고 가정합시다.
interface를 사용하는 경우라면, CatNameInfo에 neo를 추가하지 않아도 오류가 발생하지 않아 파악하기 어렵습니다.
Recrod를 사용한다면 cats 객체를 선언할 때 neo를 추가하지 않으면 에러를 반환하여 쉽게 수정할 수 있습니다.
728x90
'Language > TypeScript' 카테고리의 다른 글
[TS] Type | 04. Pick & Omit (0) | 2024.07.11 |
---|---|
[TS] outDir & rootDir (1) | 2024.07.11 |
[TS] Syntax | 07. keyof & typeof (0) | 2024.07.10 |
[TS] Syntax | 06. Union & Intersection (0) | 2024.06.28 |
[TS] Syntax | 05. 타입 별칭(Type Alias) (1) | 2024.06.28 |
Comments