드림오구
article thumbnail

1. 🌊 Union type, Intersection Type

 

 

 

1.0.1. Union Type

Union Type은 자바스크립트 논리연산자 ||와 같은 의미다.

<typescript />
type ValueType = number | string | boolean; function formatValue(value: ValueType): string { return String(value); }

 

union type으로 만들어진 ValueType 덕분에 formatValue함수는 number, string, boolean를 안전하게 전달받을 수 있어 안정성을 제공할 수 있다. 

 

<typescript />
// any type 사용 function addPrefixAny(prefix: string, value: any) { return prefix + value.toString(); // value가 toString() 메서드를 가지고 있는 지 보장하지 않는다. } // Union type 사용 function addPrefixUnion(prefix: string, value: number | string) { // number와 string 타입 모두 toString() 메서드를 가진다. return prefix + value.toString(); }

 

Union type 주의점

 

union type은 type a도 b도 될 수 있기 때문에 a와 b에 있는 속성 모두를 쓸 수 있는 것이 아닌, a와 b 모두에게 있는 겹치는 속성만 사용 가능하다.

 

1.0.2. Intersection Type 

<typescript />
type Named = { name: string; } type Aged = { age: number; } type Person = Named & Aged; let person: Person = { name: 'ogu', age: 30 };

Intersection type은 & 연산자를 사용하여 여러 타입 정의를 합치는 것을 말한다. 

 

 

 

캡틴 판교님의 타입스크립트 핸드북을 참고하였습니다.

 

 

연산자를 이용한 타입 정의 | 타입스크립트 핸드북

Union Type 유니온 타입(Union Type)이란 자바스크립트의 OR 연산자(||)와 같이 A이거나 B이다 라는 의미의 타입입니다. 아래 코드를 보겠습니다. 위 함수의 파라미터 text에는 문자열 타입이나 숫자 타입

joshua1988.github.io

 

'🐣 STUDY > Type Script' 카테고리의 다른 글

🐻 [TypeScript] 함수  (0) 2023.05.30
🐻 [TypeScript] 프로젝트 환경 구성하기  (0) 2023.05.30
🐻 [Type Script] 연습하기  (0) 2023.05.30
🐻 [TypeScript] 타입 추론  (0) 2023.05.30
🐻 [TypeScript] 기본 타입  (1) 2023.05.29
profile

드림오구

@드림오구