Union Types : OR( | ) : (발생하는 모든 케이스 중 하나 인 경우를 지정할 때 사용)
type Direction = 'left' | 'right' | 'up' | 'down';
function move(direction: Direction) {
console.log(direction);
}
move('left'); *// 'left', 'right', 'up', 'down' 중에서만 할당 가능*
type TileSize = 8 | 16 | 32;
**const tile: TileSize = 16; *// 8, 16, 32 중에서만 할당 가능
// ------------------------
type CustomSize = {
left: 10 | 20 | 30;
right: 5 | 10 | 15;
}
const size_left: CustomSize['left'] = 10; // left의 타입만 할당 가능
const size_right: CustomSize['right'] = 15; // right의 타입만 할당 가능
// CustomSize[key] 로 타입을 지정하면
// 해당 타입안의 key의 타입만 할당할 수 있게 된다.
as any;
as string;
as CustomSize['left'];*
간단한 로그인 사용 예 (function: Login → success, fail)
type SuccessState = {
response: {
body: string;
}
};
type FailState = {
reason: string;
};
type LoginState = SuccessState | FailState; *// Union Type*
function login(): LoginState {
return {
response: {
body: 'logged in!',
}
}
}
*// 분기함수*
function printLoginState(state: LoginState) {
if('response' in state) {
console.log(`${state.response.body}`);
}
else {
console.log(`${state.reason}`);
}
}
*// 실행*
let loginTry = login();
printLoginState(loginTry);
간단한 로그인 사용 예 (discriminated : 차별화 할 수 있는, 구분 할 수 있는)
type SuccessState = {
response: {
result: 'success',
body: string;
}
}
type FailState = {
result: 'fail',
reason: string;
}
type LoginState = SuccessState | FailState; *// Union Type*
function login(): LoginState {
return {
response: {
result: 'success',
body: 'logged in!',
}
}
}
*// 분기함수*
function printLoginState(state: LoginState) {
if(state.result === 'success') {
console.log(`${state.response.body}`);
}
else {
console.log(`${state.reason}`);
}
}
*// 실행*
let loginTry = login();
printLoginState(loginTry);