Typescript에서 타입을 지정해줄 수 있는 방법은 type alias, interface가 있다. 사용방법과 둘의 차이를 알아보자! 🧐
//type alias
type TFruits = {
id: number;
name: string;
};
//interface
interface IFruits {
id: number;
name: string;
}
//type alias 사용
const typeFruits: TFruits = {
id: 2,
name: 'banana',
};
//interface 사용
const interfaceFruits: IFruits = {
id: 1,
name: 'orange',
};
interface의 경우 같은 이름으로 재정의가 가능하다.
interface IFruits {
id: number;
name: string;
}
interface IFruits {
price: number;
}
const interfaceFruits: IFruits = {
id: 1,
name: 'orange',
price: 2000,
};
type UnionType = string | null;
// string
type StringType = 'hi' | 'namsun';
// number
type NumType = 1 | 2 | 3 | 4 | 5;
// object
type ObjectType = { name: 'orange' } | { price: 2000 };
// function
type FuncType = (() => number) | (() => void);
// tuple
type TupleType = [string, boolean];
const namsun: TupleType = ['dev', true];
extends
, implements
키워드를 사용할 수 있다.extends
, implements
키워드를 사용할 수 없다.type TPerson = {
name: string | undefined;
age: number | undefined;
}
interface IPerson {
name: string | undefined;
age: number | undefined;
}
interface IPerson extends TPerson {}
class PersonImpl implements TPerson {
name: string | undefined;
age: number | undefined;
}
class PersonImpl implements IPerson {
name: string | undefined;
age: number | undefined;
}
class PersonChild extends TPerson = {} //error
다음과 같은 코드가 있다고 가정해보자.
type TFruits = {
name: string;
};
interface IFruits {
name: string;
}
const typeFruits = (fruit: TFruits): TFruits => {};
const interfaceFruits = (fruit: IFruits): IFruits => {};
typeFruits와 interfaceFruits 둘 다 정의한 타입의 attribute가 없으므로 에러가 나는 코드다. 둘의 에러메세지를 비교해보자.
typeFruits
interfaceFruits
type alias는 type TFruits = { name: string; };
가 나오고, interface는 interface IFruits
가 나온다. 인터페이스는 어디서나 사용되는 새로운 이름을 만들기 때문이다. 이런 이유로 만약에 type alias에 오류가 생기면 오류메시지에는 type alias가 사용되지 않을 것이다.