κ°μ²΄ νμ μ κ°μ²΄ 리ν°λ΄κ³Ό μ μ¬νκ² λ³΄μ΄μ§λ§ νλ κ° λμ νμ μ μ¬μ©νλ€.
let poetLater: {
born: number;
name: string;
}
poetLater = {
born: 1935,
name: "Mary Oliver"
}
κ° κ°μ²΄ νμ μ κ³μ μμ±νμ§ μκ³ , κ° κ°μ²΄ νμ μ νμ λ³μΉμ ν λΉνλ λ°©λ²μ΄ λ μΌλ°μ μ΄λ€.
type Poet = {
born: number;
name: string;
}
let poetLater: Poet;
poetLater = {
born: 1935,
name: "Mary Oliver"
}
νμ μ μΆ©μ‘±νλ λͺ¨λ κ°μ ν΄λΉ κ°μΌλ‘ μ¬μ©ν μ μλ€ ?
hasBoth
λ©€λ²λ λͺ
μμ μΌλ‘ μ μΈλμ§ μμμμλ λ κ°μ λ³μΉ κ°μ²΄ νμ
μ λͺ¨λ κ°μ§λ―λ‘ λ κ°μ λ³μΉ κ°μ²΄ νμ
λ΄μ μ μΈλ λ³μλ₯Ό λͺ¨λ μ 곡ν μ μμ΅λλ€.
μ΄ν΄ μλ¨ => λμ€μ λ€μ μ½μ΄λ³΄κΈ°
λ³μμ μ¬λ¬ κ°μ²΄ νμ μ€ νλκ° λ μ μλ μ΄κΉκ°μ΄ μ£Όμ΄μ§λ©΄ TSλ ν΄λΉ νμ μ κ°μ²΄ νμ μ λμΈμΌλ‘ μ μΆνλ€.
const poem = Math.random > 0.5
? { name: "MinwooP", pages: 7 }
: { name: "MinwooP", rhymes: true };
μμ poem λ³μλ μλμ κ°μ κ°μ²΄ νμ μ λμΈμΌλ‘ μ μΆλλ€.
{
name: string,
pages: number,
ryhmes?: undefined
}
|
{
name: string,
pages?: undefined,
ryhmes: boolean
}
type PoemWithPages = {
name: string,
pages: number
}
type PoemWithRhymes = {
name: string,
ryhmes: boolean
}
type Poem = PoemWithPages | PoemWithRhymes;
const poem: Poem = Math.random > 0.5
? { name: "MinwooP", pages: 7 }
: { name: "MinwooP", rhymes: true };
poem.name; // ok
poem.pages // error
poem.rhymes // error
poem.pages
λ poem.rhymes
μ²λΌ μ μ¬μ μΌλ‘ μ‘΄μ¬νμ§ μλ κ°μ²΄μ λ©€λ²μ λν μ κ·Όμ μ ννλ€. pages
λ rhymes
λ νμ μ‘΄μ¬νλ€λ 보μ₯μ΄ μκΈ° λλ¬Έ.
if
λ¬Έμ ν΅ν΄ κ°μ²΄ νμ
λ΄λ‘μμ ν μ μκ³ , μ΄λ₯Ό ν΅ν΄ νΉμ μμ±μ μ κ·Όν μ μλ€.
if("pages" in poem){ // poemμ PoemWithPagesλ‘ μ’νμ§
poem.pages;
}else{ // poemμ PoemWithRhymesλ‘ μ’νμ§
poem.rhymes;
}
μ λμ¨ νμ μ ꡬμ±νλ νμ λ€μ 곡ν΅λ "리ν°λ΄ νμ " νλλ₯Ό ν΅ν΄μ ꡬλΆνλκ²
type PoemWithPages = {
type: 'pages'; // 리ν°λ΄ νμ
?
}
λ€μκ³Ό κ°μ΄ κ°μ²΄μ μμ±μ type
νλλ₯Ό μΆκ°νκ³ κ·Έ μμ± κ°μ typeλͺ
μ λνλΌ μ μλ€.
type PomeWithPages = {
name: string;
number: number
type: 'pages';
}
type PoemWithRhymes = {
name: string;
rhymes: boolean;
type: 'rhymes';
}
type Poem = PoemWithPages | PoemWithRhymes;
const poem: Poem = Math.random > 0.5
? { name: "MinwooP", pages: 7, type: "pages" }
: { name: "MinwooP", rhymes: true, type: "rhymes" };
if(poem.type === "pages"){
// pages νμ
}else{
// rhymes νμ
}
switch case λ¬Έμ ν΅ν΄μλ κ° typeμ ꡬλΆν μ μλ€.
switch(poem.type){
case "pages":
// ~
break;
case "rhymes":
// ~
break;
}
μ¬λ¬ κΈ°μ‘΄ κ°μ²΄ νμ μ λ³μΉ κ°μ²΄ νμ μΌλ‘ κ²°ν©ν΄ μλ‘μ΄ νμ μ μμ±ν μ μλ€.
μ λμΈ νμ κ³Ό κ²°ν©ν΄ μ¬μ©ν μλ μλ€.
type ShortPoem = { author: string } & (
| { kigo: string; type: "haiku"; }
| { metor: number; type: "villanelle"; }
);
μμ ShortPoem νμ
μ νμ author
μμ±μ κ°μ§λ©° νλμ type μμ±μΌλ‘ νλ³λ μ λμΈ νμ
μ΄λ€.
tsκ° ν΄λΉ μ΄λ¦μ μΆλ ₯νλλ‘(ν λΉ κ°λ₯μ± μ€λ₯ λ νμ κ²μ¬κΈ°κ° μΆλ ₯νλ λ©μμ§) νμ μ μΌλ ¨μ λ³μΉμΌλ‘ λ κ°μ²΄ νμ μΌλ‘ λΆν νλ©΄ μ½κΈ°κ° ν¨μ¬ μ¬μμ§λ€.
type ShortPoemBase = { author: string };
type Haiku = ShortPoemBase & { kigo: string; type: "haiku"; }
type Villanelle = { metor: number; type: "villanelle"};
type ShortPoem = Haiku | Villanelle;
λ κ°μ μμ νμ μ κ΅μ°¨ μλνλ©΄ never ν€μλλ‘ νμλλ never νμ μ΄ λλ€.