StudyForYou / ouahhan-typescript-with-react

우아한 타입스크립트 with 리액트 스터디 레포 🧵
4 stars 0 forks source link

#11[4장_1] interface와 type 키워드는 각각 타입 확장하는 방법이 다릅니다. 이 둘의 차이점이 무엇인지 말해주세요. #23

Closed hyeyoonS closed 2 months ago

hyeyoonS commented 3 months ago

❓문제

interface와 type 키워드는 각각 타입 확장하는 방법이 다릅니다. 이 둘의 차이점이 무엇인지 말해주세요.

🎯답변

소은님 답변이 완벽한 것 같아 그대로 들고 왔습니다😂

qooktree1 commented 3 months ago

interface

interface Rectangle { height: number; }

const rect = { width: 5, height: 2 }

const func = (param: Rectangle) => param.width * param.height; func(rect)


### type
- 선언 병합을 지원하지 않지만 복잡한 타입 조합이나 유니온 타입을 사용할 때 유용합니다.
```ts
interface Circle {
    figureType: 'circle';
    radius: number;
}

interface Rectangle {
    figureType: 'rectangle';
    width: number;
    height: number;
}

interface Triangle {
    figureType: 'triangle';
    width: number;
    height: number;
}

type Shape = Circle | Rectangle | Triangle;
summerkimm commented 3 months ago
hyeyoonS commented 3 months ago

타입을 확장하는 방법

1) interface에서의 타입 확장

interface BaseMenuItem {
    itemName: string | null;
    itemImageUrl: string | null;
    itemDiscountAmount: number;
    stock: number | null;
};

interface BaseCartItem extends BaseMenuItem {
    quantity: number;
}

🔎 interface는 확장과 동시에 프로퍼티 재정의가 가능하다.

interface Animal {
  name: string;
  color: string;
}

interface Dog extends Animal {
  name: "doldol"; // 타입 재 정의
  breed: string;
}

단, 프로퍼티를 재정의할 때 원본 타입을 A, 재정의된 타입을 B라고 하면 반드시 A가 B의 슈퍼 타입이 되어야 한다. 따라서 다음과 같이 name을 Number 타입으로 재정의 하는 것은 불가능하다.

interface Animal {
  name: string;
  color: string;
}

interface Dog extends Animal {
  name: number; // ❌
  breed: string;
}

⇒ Dog 타입이 Animal 타입을 확장한다는 것은 Animal 타입의 서브타입이 된다는 의미인데, 그런데 name 프로퍼티를 Number 타입으로 재정의 해 버리면 이제는 Dog는 Animal의 서브 타입이 아니게 되기 때문이다.

2. type에서의 타입 확장

// string 타입을 사용할 때
const name: string = 'capt';

// 타입 별칭을 사용할 때
type MyName = string;
const name: MyName = 'capt';
type BaseMenuItem = {
    itemName: string | null;
    itemImageUrl: string | null;
    itemDiscountAmount: number;
    stock: number | null;
};

type BaseCartItem = {
    quentity: number;
} & BaseMenuItem;
type Animal = {
  name: string;
  color: string;
};

interface Dog extends Animal {
  breed: string;
}