π Union Types
λ°μ μ μλ μΈμλ₯Ό μ ν΄μ€λ€?!
μ λμ¨ νμ (Union Type)
μ΄λ? μλ°μ€ν¬λ¦½νΈμ OR μ°μ°μ(Β )μ κ°μ΄ βAβ μ΄κ±°λ βBβμ΄λ€ λΌλ μλ―Έμ νμ .
- ORμ λλ?? π€
βοΈ Union Types μμ 1
μΈμλ₯Ό μ νν λ μμ κ·Έλ¦Όμ²λΌ μ ννκ²λ μλ €μ€. λ°μ μ μλ μΈμλ₯Ό μ ν΄μ€λ€.
- 리ν°λ΄ νμ μ νμ₯λ λλ?!π€
type Direction = "left" | "right" | "up" | "down";
function move(direction: Direction) {
console.log(direction);
}
move("down");
type TileSize = 8 | 16 | 32;
const tile: TileSize = 16;
βοΈ Union Types μμ 2
ν¨μμ νλΌλ―Έν° id
λ number
νμ
μ΄λ string
νμ
μ΄ λͺ¨λ μ¬ μ μλ€.
μ΄μ²λΌ
|
μ°μ°μλ₯Ό μ΄μ©νμ¬ νμ μ μ¬λ¬ κ° μ°κ²°νλ λ°©μ
function printId(id: number | string) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id);
}
}
βοΈ Union Types μμ 3
// function: login -> success or fail β±
type SuccessState = {
response: {
body: string;
};
};
type FailState = {
reason: string;
};
type LoginState = SuccessState | FailState;
function login(id: string, password: string): LoginState {
return {
response: {
body: "logged in!",
},
};
}
Intersection Types: & β¨
Union typeκ³Ό λ°λλλ νμ ?
Intersection type
μ΄λ?- μΈν°μΉμ νμ (Intersection Type)μ μ¬λ¬ νμ μ λͺ¨λ λ§μ‘±νλ νλμ νμ μ μλ―Έ
- λ€μν νμ λ€μ ν λ²μ λ¬Άμ΄μ μ μΈν μ μλ€.
- λ¨, μ μΈλ μ¬λ¬ νμ λ€μ λͺ¨λ μ¬μ©ν΄μΌλ§ μλ¬λ°μ νμ§ μλλ€ π
βοΈ Intersection Types μμ
&
μ°μ°μλ₯Ό μ΄μ©ν΄ μ¬λ¬ κ°μ νμ μ μλ₯Ό νλλ‘ ν©μΉλ λ°©μ
type Student = {
name: string;
score: number;
};
type Worker = {
empolyeeId: number;
work: () => void;
};
function internWork(person: Student & Worker) {
console.log(person.name, person.empolyeeId, person.work());
}
internWork({
name: "april",
score: 1,
empolyeeId: 123,
work: () => {},
});