Ted's Codding study
Union 타입 본문
Union 타입 Ted93 2024. 6. 15. 10:10
1. union 타입이란?
- 여러 타입 중 하나가 될 수 있는 값을 나타내는 방법
- 값에 허용된 타입을 두 개 이상으로 지정
- OR 연산자 (A 또는 B)
- | 기호를 사용하여 표현
2. union 타입의 사용
- 변수, 함수의 매개변수, 반환값 등에서 모두 사용 가능
- 타입의 유연성을 제공
- 무분별한 any 사용을 방지
3. union 타입의 예시(사용방법)
type UnionType = Type1 | Type2 | Type3;
type Any = string | number | boolean | string[];
let value: Any = '문자';
value = 123;
value = true;
value = ['1', '2'];
// value = {}; // Error - '{}' 형식은 'Any' 형식에 할당할 수 없습니다.
타입 별칭의 예시
- 관리자 계정 Admin
type Admin = {
id: string | number;
password: number;
};
- 사용자 계정 User
type User = {
id: string | number;
name: string;
};
type Person = Admin | User;
- 타입 별칭의 union 타입의 경우 - 중복되지 않은 타입 속성은 옵셔널(?)과 동일
즉 아래 Person은 위에 type Person = Admin | User; 코드와 동일함
type Person = {
id: string | number;
password?: number;
name?: string;
};
4. union 타입의 특징
4-1) 공통 필드 접근
- union의 모든 멤버가 공유하는 속성에만 직접적으로 접근 가능
4-2) 타입 가드 사용
- 특정 타입에만 존재하는 속성이나 메서드에 접근하기 위해서는 타입 가드를 사용 타입 가드 - 조건문을 통해 타입을 좁혀나가는 방식
4-3) 유연성과 안정성
- 다양한 타입의 사용을 가능하게 하는 유연성을 제공, 타입 가드를 적극적으로 사용하여 코드의 안정성을 향상
5. union 타입 실습
문제 1
나이가 입력될 때
숫자 : 소수점 자리가 없도록 지정하여 문자열로 반환(toFixed()) 문자 : 그대로 반환
정답
type Union = number | string;
function getAge(age: Union) {
if (typeof age === 'string') {
return age;
}
if (typeof age === 'number') {
age = age.toFixed();
return age;
}
}
console.log(getAge(12.345)); // 12
console.log(getAge('15살')); // 15살
- 참고, 타입스크립트는 자동 완성 기능을 정말 잘 제공해주는데,
type age가 string인 부분에서는 문자열 메서드를 자동완성으로 제공하고

- number 타입 조건 안에서는 number 타입의 메서드를 자동완성으로 제공한다

문제2
Union 타입을 사용한 변수 선언
string, number, boolean 중 하나의 타입을 가질 수 있는 MixedType 변수를 선언하고,
각 타입에 해당하는 값을 할당하는 예시 코드를 작성
정답
type MixedType = string | number | boolean;
let example1: MixedType;
example1 = '123';
example1 = 123;
example1 = true;
// example1 = []; - Error
문제3
함수 매개변수에 Union 타입 적용
number와 string 타입 중 하나를 매개변수로 받아,
해당 값이 number일 경우 숫자를 2배로 증가시키고,
string일 경우 그대로 반환하는 함수 doubleOrNothing을 작성
정답
function doubleOrNothing(input: number | string): void {
if (typeof input === 'number') {
console.log(input * 2);
}
if (typeof input === 'string') {
console.log(input);
}
}
doubleOrNothing(10); // 20
doubleOrNothing('hello'); // hello
문제4
Union 타입과 타입 가드를 활용한 고급 예제
Admin과 User 타입 명시
Admin은 id (number 타입)와 isAdmin (boolean 타입) 속성을,
User는 id (number 타입)와 username (string 타입) 속성 포함
두 타입의 유니온 타입을 사용하여 Person 타입을 선언하고,
id, isAdmin, username 중 적절한 속성을 가진 객체를 생성
Person 타입의 객체를 매개변수로 받아 Admin인지 User인지를 구분해 출력하는 함수 identifyPerson을 작성
정답
type Admin = { id: number; isAdmin: boolean };
type User = { id: number; username: string };
type PersonType = Admin | User;
function identifyPerson(person: PersonType) {
if ('isAdmin' in person) {
return console.log('Admin입니다');
}
if ('username' in person) {
return console.log('User입니다');
}
}
const adminPerson: PersonType = { id: 1, isAdmin: true };
const userPerson: PersonType = { id: 2, username: 'typescriptUser' };
identifyPerson(adminPerson); // Admin입니다
identifyPerson(userPerson); // User입니다
문제5
실제 프로젝트에서의 Union 활용 실제 서버와의 통신에 있어 다양한 형태의 응답을 처리하는 방법
사용자 정보가 있는 경우 : { name: string, email: string }
사용자 정보가 없는 경우 : { error: string }
정답
type Success = {
name: string;
email: string;
};
type Fail = {
error: string;
};
type UserResponse = Success | Fail;
function handleResponse(response: UserResponse) {
// in 연산자
// : 객체의 속성이 존재하면 true, 없으면 false를 반환
if ('error' in response) {
console.error(response.error);
} else {
console.log(`${response.name}, ${response.email}`);
}
}
handleResponse({ name: '테드', email: 'ted@ted.com' }); // 테드, ted@ted.com
handleResponse({ error: 'User not found' }); // User not found
노션으로 보고 싶다면?
https://short-echidna-b16.notion.site/Union-fa61e27c275243c78f67bac7980ab998?pvs=4
Union 타입 | Notion
목차
short-echidna-b16.notion.site