*// [ Type ]*
type PositionType = {
x: number;
y: number;
}
*// [ Interface ]*
interface PositionInterface {
x: number;
y: number;
}
*// object ★*
const obj1: PositionType = {
x: 1,
y: 1,
}
const obj2: PositionInterface = {
x: 1,
y: 1,
}
*// class ★*
class Pos1 implements PositionType {
x: number;
y: number;
}
class Pos2 implements PositionInterface {
x: number;
y: number;
}
*// Extends*
interface ZPositionInterface extends PositionInterface {
z: number;
}
type ZPositionType = PositionType & { z: number };
*// ---------------------*
*// Interface만 가능한 것*
*// only interfaces can be merged.*
*// type 에서는 중복되는 타입이라고 에러가 뜬다.*
{
interface PositionInterface { *// Interface 이름 동일*
x: number;
y: number;
}
interface PositionInterface { *// Interface 이름 동일*
z: number;
}
const obj: PositionInterface = {
x: 1,
y: 1,
z: 1,
}
// property 가 오버라이딩 된다.
}
Type 과 Interface 는 선언되는 방식이 비슷하다. 그러나 사용하는 목적은 다르므로 Type 과 Interface 의 정의와 개념을 잘 이해하고 있는 것이 중요하다.
Interface의 개념
Interface 는 어떤 것의 규격사항으로 다른 사람들과 의사소통 할 때, 즉 Object 와 Object간의 의사소통 할 때 Interface 를 통해서 서로 간의 상호작용을 할 수 있도록 도와주는 것이다. 그래서 API(Application Programming Interface) 는 서로 간의 약속을 할 수 있는 계약서와 같은 것이다.
Type의 개념
Type 은 우리가 어떠한 데이터를 담을 때 어떠한 데이터를 담을 수 있을지, 데이터의 모습, 데이터의 타입을 결정하는 것이다.