type Name = 'name';
let aprilName: Name;
aprilName = 'name';
function printText(s: string, alignment: "left" | "right" | "center") {
// ...
}
printText("Hello world", "left");
printText("G'day mate", "centre"); // μ΄λ΄ κ²½μ° μλ¬λ¨.
// λλ²μ§Έ μΈμμλ μΈκ°μ§μ λ¬Έμμ΄ μ€ νλλ§ μ
λ ₯ν μ μκΈ° λλ¬Έμ!!
|
μ°μ°μλ₯Ό μ΄μ©νμ¬ νμ μ μ¬λ¬ κ° μ°κ²°νλ νμ
μ λμΈμ μλ λͺ¨λ νμ μ 곡ν΅μΈ λ©€λ²μλ§ μ κ·Όν μ μλ€
λ°μ μ μλ μΈμλ₯Ό μ ν΄μ€λ€?!
μ λμ¨ νμ (Union Type)
μ΄λ? μλ°μ€ν¬λ¦½νΈμ OR μ°μ°μ(||)μ κ°μ΄ 'A' μ΄κ±°λ 'B'μ΄λ€ λΌλ μλ―Έμ νμ .
- ORμ λλ?? π€
μΈμλ₯Ό μ νν λ μμ κ·Έλ¦Όμ²λΌ μ ννκ²λ μλ €μ€.
λ°μ μ μλ μΈμλ₯Ό μ ν΄μ€λ€.
- 리ν°λ΄ νμ μ νμ₯λ λλ?!π€
type Direction = 'left' | 'right' | 'up' | 'down';
function move(direction: Direction) {
console.log(direction);
}
move('down');
type TileSize = 8 | 16 | 32;
const tile: TileSize = 16;
ν¨μμ νλΌλ―Έν° id
λ number
νμ
μ΄λ string
νμ
μ΄ λͺ¨λ μ¬ μ μλ€.
μ΄μ²λΌ
|
μ°μ°μλ₯Ό μ΄μ©νμ¬ νμ μ μ¬λ¬ κ° μ°κ²°νλ λ°©μ
function printId(id: number | string) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id);
}
}
// 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!',
},
};
}
Union typeκ³Ό λ°λλλ νμ ?
Intersection type
μ΄λ?
&
μ°μ°μλ₯Ό μ΄μ©ν΄ μ¬λ¬ κ°μ νμ μ μλ₯Ό νλλ‘ ν©μΉλ λ°©μ
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: () => {},
});