νΉμ νμ μΌλ‘ νμ μ λ²μλ₯Ό μ’νλκ°λ(νν°λ§ νλ) κ³Όμ
μ€λͺ νκΈ° μν μ¬μ μμ
interface Developer{
name: string;
skill: string;
}
interface Person {
name: string;
age: number;
}
function introduce(): Developer | Person{
return {name: 'Tony', age: 33, skill:"Iron Making"}
}
let tony = introduce();
console.log(tony.skill); // μ λμ¨ νΉμ§μ μν΄ μ κ·Ό λΆκ°
// νμ
λ¨μΈμ μ¬μ©νμ¬ μ κ·Ό
if((tony as Developer).skill){
let skill = (tony as Developer).skill;
console.log(skill);
} else if(tony as Person).age){
let age = (tony as Developer).age;
console.log(age);
}
- κ°λ μ±μ΄ λ§μ΄ λ¨μ΄μ§λλ€.
νμ κ°λλ₯Ό μ μ©νλ©΄ β
is
ν€μλ μ¬μ©
function isDeveloper(target: Developer | Person): target is Developer {
return (target as Developer).skill !== undefined; // targetμ΄ skill μ΄λΌλ κ²μ΄ μμ κ²½μ°, Developer μ·¨κΈ νλ€.
}
if(isDeveloper(tony)){
tony.skill
} else{
tony.age
}
μ°Έκ³
'π Front-End > TypeScript' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
νμ μ€ν¬λ¦½νΈμ λͺ¨λ (0) | 2022.10.23 |
---|---|
νμ νΈν(Type Compatibility) (0) | 2022.10.23 |
νμ λ¨μΈ(Type Assertion) (0) | 2022.10.23 |
νμ μΆλ‘ (Type Inference) (0) | 2022.10.23 |
μ λ€λ¦(Generics) (0) | 2022.10.23 |