[6장] 유니언 타입, 인터섹션 타입

Sheryl Yun·2023년 8월 1일
0
post-thumbnail

1. 유니언 타입

  • 여러 개 타입 중 하나의 타입만 쓰고 싶을 때 사용
    • 형태: | (OR 연산자)

에러 예시

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

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

두 타입을 유니언으로 연결한 후 someone.age를 출력하면 age가 타입 중 포함이 되어 있는데도 에러 발생

function introduce(someone: Person | Developer) {
	console.log(someone.age);
}
  • someone은 Person 또는 Developer 타입으로 Person의 age 속성을 참조하면 에러가 안 날 것 같지만, 타입스크립트 입장에서는 참조하고 있는 someone이 Person 타입인지 Developer 타입인지 구분할 수 없음

해결: 타입 가드로 타입 좁히기

in 연산자와 typeof 키워드의 2가지 해결 방법 있음

1. in 연산자

  • 객체 안(in)에 특정 속성이 있는지 여부를 확인
function introduce(someone: Person | Developer) {
	if ('age' in someone) {
    	console.log(someone.age);
        return;
    }
    
    if ('skill' in someone) {
    	console.log(someone.skill);
        return;
    }
}

2. typeof 키워드

  • 데이터 타입을 문자열로 반환하여 타입 확인
function logText(text: string | number) {
	if (typeof text === 'string') {
    	console.log(text.toUpperCase());
    }
    
    if (typeof text === 'number') {
    	console.log(text.toLocaleString());
    }
}

결론

  • 유니언 타입으로 여러 개의 타입을 조합해서 사용할 때는 in이나 typeof 연산자를 사용하여 사용할 타입을 구체적으로 확정해줘야 타입스크립트가 타입 부여를 명확히 할 수 있다.

2. 인터섹션 타입

  • 타입 2개를 하나로 합쳐서 사용하는 것으로 타입들의 모든 속성 포함
    • 형태: & (AND 연산자)
interface Avenger {
	name: string;
}

interface Hero {
	skill: string;
}

function introduce(someone: Avenger & Hero) {
	console.log(someone.name);
    console.log(someone.skill);
}
  • 합쳐진 타입 중 일부 속성만 쓰고 싶다면 옵셔널 연산자(?) 사용
    • 예: someone?.name
profile
데이터 분석가 준비 중입니다 (티스토리에 기록: https://cherylog.tistory.com/)

0개의 댓글