front/ts
[타입스크립트] 인터페이스와 타입
juniKang
2022. 7. 21. 20:51
인터페이스와 타입의 특성에 대해 알아보자.
1. primitive type rename
인터페이스는 primitive type으로 선언은 불가능하지만, 타입은 가능하다. 인터페이스는 오직 object type을 선언할 때만 사용할 수 있다.
// ❌ 불가능
interface InterfaceString = string;
interface InterfaceString extends string;
// ✔ 가능
type TypeString = string;
2. 확장
인터페이스는 동일한 이름을 사용해서 확장이 가능하다.
// ✔ 가능
interface Fruit {
apple: string
}
interface Fruit {
banana: string
}
const fruits: Fruit = {
apple: '사과',
banana: '바나나',
}
동일한 이름으로 확장 할 때, 프로퍼티의 타입을 늘려줄 수는 없다.
// ❌ 불가능
interface Fruit {
apple: string
}
interface Fruit {
apple: string | number
}
// Error : Subsequent property declarations must have the same type.
// Property 'apple' must be of type 'string', but here has type 'string | number'.ts(2717)
타입은 인터페이스 처럼 동일한 이름을 사용해서 확장할 수 없다.
// ❌ 불가능
type Fruit = {
apple: string
}
type Fruit = {
banana: string
}
// Error: Duplicate identifier 'Fruit'.
대신, & (intersections : 교차) 를 사용해서 확장할 수 있다.
// ✔ 가능
type Apple = {
apple: string
}
type Banana = {
banana: string
}
type Fruit = Apple & Banan & {
orange: string
}
const fruit: Fruit = {
apple: '사과',
banana: '바나나',
orange: '오렌지',
}
3. 확장 - 상속
인터페이스는 extends를 사용해서 상속받을 수 있다.
// ✔ 가능
interface Apple {
apple: string
}
interface Banana {
banana: string
}
interface Fruit extends Apple, Banana {
orange: string
}
const fruit: Fruit = {
apple: '사과',
banana: '바나나',
orange: '오렌지',
}
특이한 점은, type으로 부터도 상속받을 수 있다.
// ✔ 가능
type Apple {
apple: string
}
type Banana = {
banana: string
}
interface Fruit extends Apple, Banana {
orange: string
}
const fruit: Fruit = {
apple: '사과',
banana: '바나나',
orange: '오렌지',
}
타입은 인터페이스나 다른 타입을 상속받을 수 없다. 그러나 인터페이스를 intersection(&)으로 사용할 수는 있다.
// ❌ 불가능
interface Apple {
apple: string;
}
type sonApple extends Apple {...}
interface Banana {
banana: string;
}
type sonBanana implements Banana {...}
// ✔ 가능
interface Apple {
apple: string
}
type Fruit = Apple & {
banana: string
}
인터페이스를 타입으로 변환할 수 있고, 타입을 인터페이스에서 상속받을 수 있다.
// ✔ 가능
interface Apple {
apple: string;
}
type TypeApple = Apple;
interface Fruit extends TypeApple {
banana: string;
}