teklog

TypeScript 입문하기 3 - Alias

2022/09/05

n°4

category : TypeScript

**migrated from old blog


Type Alias : type

Interface와 유사하게 type을 정의하는 방식이다.



interface TypeInter {
age : number
name : string
}

type TypeAlias = {
age : number,
name : string
}

const person1 : TypeInter {
age : 12,
name: 'person1'
}

const person2 = {} as TypeAlias;
person2.age = 32;
person2.name = 'person2'

// 동일한 결과


💡 Interface와 유일한 차이점은 2가지


  • 원시값, 튜플, 유니언 타입을 타입으로 바로 지정할 수 있다.
  • 상속이 일어나지 않는다.



Type Alias는 원시값, tuple, union type을 지정할 수 있다.

Interface는 기본적으로 객체 형태로 선언되기 때문에 변수명 = 타입 과 같은 방식으로 타입을 지정할 수 가 없다.



원시값 예시
type Alias = string;

interface Inter {
Inter : string;
Union : string | number;
}

const alias : Alias = 'abc'
// compile 에러 
const inter : Inter = 'abc'
// 'string' 형식은 'Inter' 형식에 할당할 수 없습니다.ts(2322)

맞는 방법 
const inter : Inter['Inter'] = 'inter'
const UnionInter : Inter['Union'] = 32


Type Alias는 상속(extends)이 불가능하다.

하지만 Interface는 가능하다.



type Alias1 = {
  age: number
}

type Alias2 extends Alias1  = {
 name: string
}

// 컴파일 에러

interface parentInter {
  age : number
}

interface childInter extends parentInter {
 name: string 
}

const child : childInter = {
  age : 12,
  name: 'good boy'
}