본문 바로가기
Understanding TypeScript

연산자를 활용한 TypeScript의 Type

by Luciditas 2023. 4. 15.
728x90

TypeScript는 연산자를 이용해 타입을 정할 수 있다.

이 중 | 연산자를 이용한 타입을 유니온 타입이라고 하고 & 연산자를 이용한 타입을 인터섹션 타입이라고 한다.

 

Union Type

| 연산자를 이용해 JavaScript의 or연산자와 같이 "A이거나 B이다"라는 뜻이다.

 

function printValue(value: number|string): void {
	if (typeof value === 'number'){
    	console.log(`The value is a number : ${value}`;
        } else {
        	console.log(`The value is a string : ${value}`);
        }
 }
 
 
 printValue(10) // The value is a number : 10
 printValue('hello') The value is a string : hello

 

위 코드에서 printValue 함수는 숫자 또는 문자열 값을 입력받고 있다.이 때 Union Type을 이용해 number | string 타입으로 지정한다.이후 입력된 값의 타입을 typeof 연산자를 사용해 검사한 후 해당 값이 숫자인 경우와 문자열인 경우를 각각 출력한다.

 

Union Type을 사용할 때 주의할 

 

Union Type인 값이 있으면 Union에 있는 모든 type의 공통으로 해당하는 property에만 접근할 수 있다.

interface Developer {
  name: string;
  skill: string;
}

interface Person {
  name: string;
  age: number;
}

 

Interface를 사용해 Developer와 Person을 정의했다.

 

function askSomeone(someone: Developer | Person) {
	console.log(someone.name);
}

 

그러나 실질적으로 askSomeone 함수 내부에서는 Developer와 Person이 갖고 있는 공통 property인 name에만 접근할 수 있다. TypeScript는 공통되고 보장된 property만 제공하기 때문이다.만일 나머지 property에도 접근하고 싶다면 Type Guard를 사용해야한다.

 

Type Guard란?TypeScript에서 type을 보호하기 위해 사용되는 기능이다. Type Guard는 특정 코드 블럭에서 type의 범위를 제한하여 해당 코드 블럭 안에서  type 안정성을 보장해준다.

 

Type Guard를 이용한 코드

function askSomeone(someone: Developer | Person) {
  // in 연산자 : 타입스크립트에서 객체의 속성이 존재하는지를 체크하는 연산자
  // in 연산자는 객체의 속성 이름과 함께 사용하여 해당 속성이 객체 내에 존재하는지 여부를 검사
  if ('skill' in someone) {
    console.log(someone.skill);
  }

  if ('age' in someone) {
    console.log(someone.age);
  }
}

 

Interaction Type

 

Interaction Type은 둘 이상의 type을 결합하여 새로운 type을 만드는 방법이다.

& 연산자를 사용해 표현한다.

 

interface Developer {
  name: string;
  skill: string;
}

interface Person {
  name: string;
  age: number;
}

type User = Developer & Person;

 

여기서 user 변수는 Developer, Person 각각에 정의 된 속성 모두를 받는다.

여기서 type은 type alias에서 다시 정리하겠다.

Interaction Type은 type을 연결해 하나의 단일 type으로 표현 가능하기 때문에 Type Guard가 필요없다.

 

interface Developer {
  name: string;
  skill: string;
}

interface Person {
  name: string;
  age: number;
}

function askSomeone(someone: Developer & Person) {
  console.log(someone.age);
	console.log(someone.name);
	console.log(someone.skill);
}

 

위 코드는 Developer와 Person을 하나의 type으로 묶어서 사용하고 있다.

따라서 askSomeone 함수 내에 정의된 property에 전부 접근이 가능하다.

 

Interaction Type을 사용할 때 유의할 점

 

Interaction Type은 Type Guard가 필요하지 않지만 Developer와 Person이라는 새로운 교집합을 만들어 내는 것이기 때문에 전달인자를 전달시 모든 property를 전부 보내줘야한다.

 

(반대로 Union Type은 Type Guard가 필요하지만 전달인자를 전달할 때 선택지가 생긴다.)

 

interface Developer {
  name: string;
  skill: string;
}

interface Person {
  name: string;
  age: number;
}

function askSomeone(someone: Developer | Person) {
	//이런 식으로 프로퍼티에 접근할 수 있습니다.
  if ('skill' in someone) {
    console.log(someone.skill);
  }

  if ('age' in someone) {
    console.log(someone.age);
  }
}

//유니온 타입은 전달인자를 전달할 때 선택지가 생깁니다.
askSomeone({name: '김코딩', skill: '웹 개발'});
askSomeone({name: '김코딩', age: 20});

function askSomeone2(someone: Developer & Person) {
	//타입 가드를 사용하지 않아도 모든 프로퍼티에 접근할 수 있습니다.
  console.log(someone.age);
	console.log(someone.name);
	console.log(someone.skill);
}

//그러나 인터섹션 타입으로 결합하게 된다면 전달인자를 전달할 때 선택지가 없습니다.
askSomeone2({name: '김코딩', skill: '웹 개발', age:20});
728x90

'Understanding TypeScript' 카테고리의 다른 글

[TS] TypeScript의 열거형  (0) 2023.04.19
TypeScript에서의 함수  (0) 2023.04.13
TypeScript의 타입  (0) 2023.04.11
What is TypeScript?  (0) 2023.03.13