728x90
์ ๋์จ ํ์ ์ ํ์ ์คํฌ๋ฆฝํธ์์ ์ฝ๋ฉํ ๋ ๊ต์ฅํ ๋ง์ด ์ฐ๊ฒ ๋ ๊ฒ์ด๋ค.
OR ๋๋ ํฉ์งํฉ์ผ๋ก ์ดํดํ๋ฉด ์ถฉ๋ถํ ๊ฒ์ด๋ค.
type Direction = "left" | "right" | "up" | "down";
function move(direction: Direction) {
console.log(direction);
}
type TileSize = 8 | 16 | 32;
const tileA: TileSize = 16;
//const tileB: TileSize = 10; //10 ํ์์ TileSize ํ์์ ํ ๋นํ ์ ์์ต๋๋ค.
<ํ์ฉ ์์ >
//function : login -> success, fail
type SuccessState = {
response: {
body: string;
};
};
type FailState = {
reason: string;
};
function login(): SuccessState | FailState {
return {
response: {
body: "logged in!",
},
};
}
ํ๋จ๊ณ ๋ ๋ฆฌํํ ๋ง
type SuccessState = {
response: {
body: string;
};
};
type FailState = {
reason: string;
};
type LoginState = SuccessState | FailState;
function login(): LoginState {
return {
response: {
body: "logged in!",
},
};
}
์ค๋ฌด ์คํ์ผ๋ก ๊ฐ๋ฉด ์ด์ ํ๋ผ๋ฏธ์ค ๋์ !
function login(id: string, password: string): Promise<LoginState> {
/.../
};
}
<์ฐ์ต> for...in๊ณผ ํจ๊ป ์จ๋ณด๊ธฐ
type SuccessState = {
response: {
body: string;
};
};
type FailState = {
reason: string;
};
type LoginState = SuccessState | FailState;
function printLoginState(state: LoginState) {
if ("response" in state) {
console.log(`๐ ${state.response.body}`);
} else {
console.log(`๐ญ ${state.reason}`);
}
}
let ์
์ฅ: SuccessState = {
response: {
body: "์
์ฅ์๋ฃ!",
},
};
printLoginState(์
์ฅ); //๐ ์
์ฅ์๋ฃ!
์ ์์ ๋ ์ฌ์ค ๊ด์ฐฎ์ ์คํ์ผ์ ์๋๋ฏ๋ก
Discriminated Union ์ ๋ ์ถ์ฒ
728x90
'TypeScript > ํ์ ์คํฌ๋ฆฝํธ TypeScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ์ ํ์ ! Discriminated Union (0) | 2022.04.15 |
---|---|
ํ์ ์คํฌ๋ฆฝํธ 1์ฅ ์ฐ์ต๋ฌธ์ | ํ์ ์คํฌ๋ฆฝํธ์ ์ถ๋ก (0) | 2022.04.15 |
ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ์ฐ๋ ์ด์ , type alias์ String Literal Types (0) | 2022.04.15 |
์คํ๋ ๋ ์ฐ์ฐ์, ๋ฐฐ์ด, ํํ (0) | 2022.04.15 |
ํ์ ์คํฌ๋ฆฝํธ ๋ง๋ณด๊ธฐ (0) | 2022.03.28 |