type vs interface in TypeScript

jisookim·2024년 10월 14일

만약 추상 클래스를 다른 클래스들이 특정 모양을 따르도록 하기 위한 용도로 사용한다면, class 보다는 interface 를 사용하는 것이 좋다.

class Player extends User{}
// 보다는
class Player implements User{}
// 를 사용하는 것이 좋음.

인터페이스는 자바스크립트에서 보이지는 않을 것! 타입스크립트 용어이다.

📍타입 vs 인터페이스

type PlayerA = {
	name: string;
};

const plA : PlayerA = {
	name: "playerA",
};

interface PlayerB {
	name: string;
}

const plB : PlayerB = {
	name: "playerB",
};

📍타입 상속하기 example

type PlayerA = {
	name: string;
};

type PlayerAA = PlayerA & {
	lastName: string;
};

const plA: PlayerAA = {
	name: "playerA",
	lastName: "AA",
};

📍인터페이스 상속하기 example

interface PlayerB {
	name: string;
}

interface PlayerC extends PlayerB {
	lastname: string;
}

const plC : PlayerC = {
	name: "playerC",
	lastname: "xxx"
}

나중에 property를 추가하고 싶으면 어떻게 해야 할까?
type은 재정의해서 다른 것들을 더 추가해줄 순 없음. 왜냐하면 타입중복이 안되기 때문!
-> 그러나 굳이굳이 type으로 무언가를 더 추가해주고 싶다면, 상속을 받아서 (PlayerA & {sth...}) 새로운 type을 만들어야 한다!

하지만 interface는, 가능하다!

interface PlayerB {
	name: string;
}

interface PlayerC extends PlayerB {
	lastname: string;
}

interface PlayerC {
	hobby: string,
    age: number
}

const plC : PlayerC = {
	name: "playerC",
	lastname: "xxx",
    hobby: "drawing",
    age: 20
}

interface와 type모두 abstract class를 대체해서 쓸 수 있다.

type PlayerA = {
	firstName: string;
};

interface PlayerB {
	firstName: string;
}

class User2 implements PlayerA {
	constructor(public firstName: string) {}
}

class User3 implements PlayerB {
	constructor(public firstName: string) {}
}

📍TypeScript Docs에서는...

클래스나 오브젝트의 모양을 정의하고 싶으면 인터페이스를 사용하고, 다른 모든 경우(ex - type alias, 특정 값으로 타입을 제한하려는 경우...)에는 type를 사용하는 것이 관례.

Almost all features of an interface are availiable in type, the key distinction is that a type can not be re-opened to add new properties vs an interface which is always extendable.

0개의 댓글