[타입스크립트] TypeScript의 Type과 Interface

minidoo·2020년 10월 29일
0

타입스크립트

목록 보기
3/6
post-thumbnail

Type Alias

Type Alias 는 하나 이상의 타입을 조합해 별칭을 부여한다.

아래의 예시는 가장 간단하게 타입을 선언할 수 있는 방법이다.
짧고 간단한 코드에서는 문제가 없지만 규모가 큰 프로젝트의 경우 타입의 가시성이 좋기를 바란다.

let age: number = 20;

이때 사용하는 것이 Type Alias 이다.

type Age = number;
let age: Age = 20;

다양한 방법으로 타입을 선언할 수 있다.

type AType = string;
type BType = string | number | boolean;
type CType = { 
  name: string,
  age: number,
  isValid: boolean
};


let AUser: AType = 'A';
let BUser: BType = false;
let CUser: CType = {
  name: 'miniddo',
  age: 20,
  isValid: true
};

Interface

interface 는 타입스크립트와 여러 객체를 정의하는 일종의 규칙이다.
인터페이스는 보통 앞에 I 를 별칭으로 사용한다.

interface IPalette {
  id: number,
  color: string,
  isValid?: boolean
}

각 항목의 구분으로 , 또는 ; 를 사용할 수 있으며, 없어도 무관하다.
또한 속성에 ? 를 붙이면 선택적 속성으로 정의할 수 있다.

const Red: IPalette = {
  id: 0,
  color: 'red',
  isValid: true
}

const Orange: IPalette = {
  id: 1,
  color: 'orange'
}

// '?' 를 붙이지 않는 속성은 반드시 사용해야 한다.
// 'color' is declared here
const Pink: IPalette = {
  id: 2
}

Type Alias와 Interface 차이점

  • 타입 별칭을 이용해서 기본 타입에 새로운 이름을 붙일 수 있다.
type Name = string;
type Age = number;
type multi = string | number | boolean;
  • 타입 별칭은 실제로 새 타입을 생성하지 않는다. 타입 별칭 관련 에러가 발생했을 때, 타입 별칭이 아닌 실제 타입을 보여준다. 반면 인터페이스는 실제로 새 타입을 생성한다.
type Name = string;
const name: Name = 1;	// Type 'number' is not assignable to type 'string'
interface IUser {
  name: string,
  age: number
};

const user: IUser = {
  name: 'miniddo',
  age: '20'	// The expected type comes from property 'age' which is declared here on type 'IUser'
};
  • 인터페이스는 extends 키워드로 확장할 수 있다.
interface Shape {
  color: string
};

interface Square extends Shape {
  width: number,
  height: number
}

const mySquare: Square = {
  color: 'red',
  width: 10,
  height: 15
}

참고 사이트

https://heropy.blog/2020/01/27/typescript/

0개의 댓글