본문 바로가기
TypeScript

[TypeScript] 색다르게 타입도 변수에 담아서 쓰자(type alias)

by 딩박사 2023. 10. 18.
반응형

* 본 포스팅은 필자가 개인적으로 학습한 내용정리 및 리뷰를 위해 포스팅합니다.


 

 

type Userid = string | number | undefined;
let 아이디 :Userid = abcd;

type alias를 만들어서 변수에 타입을 담아서 이용한다.

 

 

type Username = {
    readonly name : string
}

const 사용자명 :Username = {
    name : 'KIM'
}

▲ readonly를 사용하면 추후 object 자료 수정을 막을 수 있다!!

 

 

type Id = string;
type Pwd = number;
type Email = Id | Pwd;

▲ union type으로 타입을 합치기도 가능하다.

 

 

type Mathscore = { x : number };
type Englishscore = { y : number };

type Totalscore = Mathscore & Englishscore;

let total :Totalscore = { x : 80, y : 77 }

▲ & 연산자로 object 타입 합치기도 가능하다(단! 같은 이름의 type 변수 재정의는 불가능하다)

 

 

 

 

 

 

 

참고 : https://radlohead.gitbook.io/typescript-deep-dive/type-system/readonly

 

읽기 전용(readonly) - TypeScript Deep Dive

기본적으로 readonly는 내가 속성을 변경하지 못함을 보장하지만, 객체를 다른 사람에게 넘길 경우에는 이것이 보장되지 않고 그 다른 사람은 객체의 속성을 변경할 수 있습니다 (타입 호환성 문

radlohead.gitbook.io

 

 

결론

변수를 생성할 때마다 타입을 정하기보다는 type alias를 활용해서 타입을 변수화하여 이용하면 효율적일 것 같다.

반응형

댓글