
π κ°λ
π κ°μ ν¨μ μ΄λ¦μΈλ°, μ¬μ©νλ λ°©λ²μ΄ μ¬λ¬ κ° μλ κ²
νλμ ν¨μμ μ¬λ¬ νμ
μ λ§€κ°λ³μλ₯Ό μ μνλ λ°©μ
μλ₯Ό λ€μ΄:
func(1) π νλλ§ λ£μΌλ©΄ Γ20
func(1,2,3) π 3κ° λ£μΌλ©΄ ν©
function func(a: number): void;
function func(a: number, b: number, c: number): void;
π "μ΄ ν¨μ μ΄λ κ²λ μ°κ³ , μ λ κ²λ μ¨μ" λΌκ³ 미리 μ μΈ
function func(a: number, b?: number, c?: number) {
π μ€μ ν¨μλ νλλ§ μ‘΄μ¬
π λμ ?λ‘ μ νμ νλΌλ―Έν° μ²λ¦¬
if (typeof b === 'number' && typeof c === 'number') {
console.log(a + b + c);
} else {
console.log(a * 20);
}
π λ€μ΄μ¨ κ°μ λ°λΌ λ€λ₯΄κ² μ€ν
β μλ°μ€ν¬λ¦½νΈλ μ€λ²λ‘λ© μμ
π κ·Έλμ νμ
μ€ν¬λ¦½νΈκ° "νμ
λ§" λμμ£Όλ κ²
π μ€μ μ€νμ κ²°κ΅ νλμ ν¨μ
π "νμ λ§ μ¬λ¬ κ°μ²λΌ 보μ΄κ² νκ³ , μ€μ ν¨μλ νλ"
π λ¬Έμ μν©
type Animal = Dog | Cat;
π DogμΈμ§ CatμΈμ§ λͺ¨λ¦ π±
function isDog(animal: Animal): animal is Dog {
return (animal as Dog).isBark !== undefined;
}
π animal is Dog β νμ μ’νκΈ° (μ΄κ² μ€μ!)
π μ΄ λ»:
"μ΄ ν¨μκ° trueλ©΄ animalμ DogμΌ"
π νμ
μ€ν¬λ¦½νΈκ° μ΄ν΄ν¨
π μ½κ² λ§νλ©΄
if (isDog(animal)) {
π νμ
μ€ν¬λ¦½νΈ μκ°:
"μ μ Dog νμ μ΄λ€"
function isCat(animal: Animal): animal is Cat {
return (animal as Cat).isScratch !== undefined;
}
function warning(animal: Animal) {
if (isDog(animal)) {
// Dog νμ
νμ
} else if (isCat(animal)) {
// Cat νμ
νμ
}
}
β κ·Έλ₯ νλ©΄ μ€λ₯λ¨
animal.isBark β
π μ?
π DogμΈμ§ CatμΈμ§ λͺ¨λ₯΄λκΉ
if (isDog(animal)) {
animal.isBark β
}
β μ¬μ© μμ
function warning(animal: Animal) {
if (isDog(animal)) {
console.log("κ°μμ§");
} else {
console.log("κ³ μμ΄");
}
}
π "μ΄ κ°μ΄ μ΄λ€ νμ μΈμ§ TSμκ² μλ €μ£Όλ ν¨μ"
β μ€μ 1
function func(a:number)
function func(a:number, b:number)
π ꡬν ν¨μ λ°λ‘ μ λ§λ€λ©΄ μλ¬
β μ€μ 2
animal.isBark
π λ°λ‘ μ κ·Ό β (νμ λͺ¨λ¦
β μ€μ 3
return animal.isBark !== undefined;
π νμ λ¨μΈ μμ΄ μ°λ©΄ μλ¬ κ°λ₯
β μμ νκ²:
(animal as Dog).isBark