728x90
์ฐจ๋ณํ(๊ตฌ๋ถ) ํ ์ ์๋ Union
์๋ ์ฝ๋๋ฅผ ๊ฐ์ ํด๋ณด์
type SuccessState = {
response: {
body: string;
};
};
type FailState = {
reason: string;
};
type LoginState = SuccessState | FailState;
function login(): SuccessState | FailState {
return {
response: {
body: "logged in!",
},
};
}
function printLoginState(state: LoginState) {
if ("response" in state) {
console.log(`๐ ${state.response.body}`);
} else {
console.log(`๐ญ ${state.reason}`);
}
}
let ์
์ฅ: SuccessState = {
response: {
body: "์
์ฅ์๋ฃ!",
},
};
printLoginState(์
์ฅ); //๐ ์
์ฅ์๋ฃ!
์ ๋์จ ํ์ ์ ์ฌ์ฉํ ๋, ์ด๋ค ์ผ์ด์ค๋ ๊ณตํต ํ๋กํผํฐ๋ฅผ ๊ฐ์ง๊ณ ์์์ผ๋ก์ ์กฐ๊ธ ๋ ๊ตฌ๋ถํ๊ฒ ์ฝ๊ฒ ๋ง๋ค์ด์ฃผ์.
์๋์ ๊ฐ์ด
type SuccessState = {
result: "success";
response: {
body: string;
};
};
type FailState = {
result: "fail";
reason: string;
};
type LoginState = SuccessState | FailState;
function login(): SuccessState | FailState {
return {
result: "success",
response: {
body: "logged in!",
},
};
}
function printLoginState(state: LoginState) {
if (state.result == "success") {
console.log(`๐ ${state.response.body}`);
} else {
console.log(`๐ญ ${state.reason}`);
}
}
let ์
์ฅ: SuccessState = {
result: "success",
response: {
body: "์
์ฅ์๋ฃ!",
},
};
printLoginState(์
์ฅ); //๐ ์
์ฅ์๋ฃ!
728x90
'TypeScript > ํ์ ์คํฌ๋ฆฝํธ TypeScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ์ ์คํฌ๋ฆฝํธ ๊ณ์ฐ๊ธฐ ํจ์ ๋ง๋ค๊ธฐ (0) | 2022.04.17 |
---|---|
Union๊ณผ ๋ ๋ค๋ฅธ Intersection ํ์ (0) | 2022.04.15 |
ํ์ ์คํฌ๋ฆฝํธ 1์ฅ ์ฐ์ต๋ฌธ์ | ํ์ ์คํฌ๋ฆฝํธ์ ์ถ๋ก (0) | 2022.04.15 |
์ง์ ํ ํ์ ์คํฌ๋ฆฝํธ์ ์์, Union ํ์ (0) | 2022.04.15 |
ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ์ฐ๋ ์ด์ , type alias์ String Literal Types (0) | 2022.04.15 |