Type Alias VS Interface

Jung taeWoong·2021년 5월 9일
0

typescript

목록 보기
7/11
post-thumbnail

Type Aliace VS Interface

Type Aliace 정의

  • 어떠한 것을 구현할 목적이 아닌 데이터를 담을 목적으로 만들때 Type사용

Interface 정의

  • 어떤것의 규격사항
  • Object간의 의사소통을 할 때 정해진 interface를 토대로 상호작용을 도와줌
  • 어떤 특정한 규격을 정의하거나 이 규격을 통해서 어떤 것이 구현된다면 Interface를 사용

공통점

  1. Type을 기술하는 방법
type PersonType = {
  name: string;
  age: number;
}
interface PersonInterface {
  name: string;
  age: number;
}

const person1: PersonType = {
  name: 'woong',
  age: 27,
}
const person2: PersonInterface= {
  name: 'tack',
  age: 27
}
  1. implements(구현)과 exetnds(상속)
    • Type Alias 내에 union이 사용된 경우 사용 X
    • 정적으로 모양을 알수있는 객체 타입만 동작
class Person1 implements PersonType {
  name: string;
  age: number;
}
class Person2 implements PersonInterface {
  name: string;
  age: number;
}
// extends
interface GenderPersonInterfcae extends PersonInterface {
  gender: string;
}
type GenderPersonType = PersonType & {gender: string};

차이점

  1. Declaration Merging (Interface)
    • Interface는 같은 이름으로 여러 번 선언을 해도 컴파일 시점에서 합쳐진다.
    • public API에 사용되는 타입은 항상 interface로 작성해야하는 이유
interface PersoneInterface {
  name: string;
  age: number;
}
interface PersonInterface {
  gender: string;
}
  1. Computed Property (Type Alias)
  • 대괄호([])안에 표현식(expression)을 이용해 객체의 key값을 정의하는 문법
    - 프로퍼티의 키로서 변수를 받을 수 있다.
  • 더 활용성이 높은 타입을 선언하고 사용가능
type Person = {
  name: string,
  age: number,
}
type Name = Person['name']; // string
profile
Front-End 😲

0개의 댓글