- 타입 확장은 기존 타입을 사용해서 새로운 타입을 정의하는 것을 말한다. 기본적으로 타입스크립트에서는
interface
와type
키워드를 사용해서 타입을 정의하고extends
, 교차 타입, 유니온 타입을 사용하여 타입을 확장한다. - 타입을 확장하면 중복된 코드를 줄일 수 있고 더 명시적인 코드를 작성할 수 있다.
type BaseMenuItem = { itemName: string | null; itemImageUrl: string | null; itemAmount: number; stock: number | null; } type BaseCartItem = { quantity: number; } & BaseMenuItem;
- 요구 사항이 늘어날 때마다 타입을 확장하여 새로운 타입을 정의할 수 있다. 예를 들어 요구 사항이 변경되어도 BaseCartItem 타입만 수정하면 된다.
interface EditableCartItem extends BaseCartItem { isSoldOut: boolean; optionGroups: string[]; } interface EventCartItem extends BaseCartItem { orderable: boolean; }
하나의 타입에 여러 속성을 추가하는 방식(Not Good)
menu
는 Menu 타입의 원소를 갖기 때문에text
속성에 접근할 수 있다. 하지만 해당 배열의 모든 원소는text
라는 속성을 가지고 있지 않으므로 에러가 발생한다.
interface Menu { name: string; image: string; gif?: string; } const menu: Menu[] = [{ name: 'a', image: 'a' }]; const menuWithGif: Menu[] = [{ name: 'a', image: 'a', gif: 'a' }]; menu.map(item => item.gif);
타입을 확장하는 방식(Good)
- 타입을 확장하면 컴파일 단계에서 해당 속성이 없다는 것을 알 수 있다.
- 주어진 타입에 무분별하게 속성을 추가하여 사용하는 것보다 타입을 확장해서 사용하는 것이 좋다. 적절한 네이밍을 사용해서 타입의 의도를 명확히 표현할 수도 있고, 코드 작성 단계에서 예기치 못한 버그도 예방할 수 있다.
interface Menu { name: string; image: string; } interface GifMenu extends Menu { gif: string; } const menu: Menu[] = [{ name: 'a', image: 'a' }]; const gifMenu: GifMenu[] = [{ name: 'a', image: 'a', gif: 'a' }]; menu.map(item.gif) // 타입 에러
'TypeScript' 카테고리의 다른 글
[TS] 식별할 수 있는 유니온, Exhaustiveness Checking (1) | 2025.01.25 |
---|---|
[TS] 타입 가드 (1) | 2025.01.24 |
[TS] 제네릭 사용법 (0) | 2025.01.22 |
[TS] 타입 조합 (0) | 2025.01.21 |
[TS] 문자열 템플릿 리터럴 타입 (0) | 2025.01.17 |