728x90
λ°˜μ‘ν˜•

🎈주제:  Ts의 νƒ€μž… κ°€λ“œ

 

1.  νƒ€μž… κ°€λ“œλž€?

νƒ€μž…μ„ μ’ν˜€λ‚΄κΈ° μœ„ν•΄ μ‚¬μš©ν•˜λŠ” κΈ°μˆ μ΄λ‹€.

λ„ˆλ¬΄λ„ˆλ¬΄ μ€‘μš”ν•˜λ‹€!

 

1-1. typeof

Jsμ—μ„œ 많이 ν™œμš©ν•΄ 봀을 μΉœκ΅¬λ‹€ :)

막아버렸닀!!

function print(value: string | number): string {
    if(typeof value === 'number') {
        return String(value);
    }

    if(typeof value === 'string') {
        return value;
    }

    return value;
}

이러면 μ•ˆμ „ν•΄μ§„λ‹€..

 

1-2. in

  • in μ—°μ‚°μžλŠ” λͺ…μ‹œλœ 속성이 λͺ…μ‹œλœ 객체에 μ‘΄μž¬ν•˜λ©΄ trueλ₯Ό λ°˜ν™˜ν•œλ‹€.
  • 이미 Js에 μžˆλŠ” νƒ€μž… 검사 μ—°μ‚°μžμ΄λ‹€.
  • λ‹€μ‹œ 말해, 객체가 νŠΉμ • 속성을 κ°€μ§€κ³  μžˆλŠ”μ§€ 검사λ₯Ό ν•΄μ€€λ‹€κ³  μƒκ°ν•˜λ©΄ λœλ‹€.

 

interface Dog {
    name: string;
    bark(): '멍멍';
}

interface Cat {
    name: string;
    meow(): 'λƒμ˜Ή';
}

function sayAnimal(animal: Dog | Cat) {
    if('bark' in animal) {
        animal.bark();
    }

    if('meow' in animal) {
        animal.meow();
    }
}

 

1-3. instanceof

 

μƒμ„±μžμ˜ prototype 속성이 객체의 ν”„λ‘œν† νƒ€μž… 체인 μ–΄λ”˜κ°€ μ‘΄μž¬ν•˜λŠ”μ§€ νŒλ³„ν•œλ‹€.

이 μΉœκ΅¬λ„ Js에 μ‘΄μž¬ν•œλ‹€.

 

function getDate(date: Date | string): Date {
    if(date instanceof Date) {
        return date;
    }

    return new Date(date);
}

 

1-4. μ‚¬μš©μž μ •μ˜

 

μ•žμ „μ— λ³Έ νƒ€μž…κ°€λ“œλ“€μ΄ μ’€ 아쉽닀고 λŠκ»΄μ§„λ‹€.

μƒˆλ‘œμš΄ μ‚¬μš©μž μ •μ˜ νƒ€μž… κ°€λ“œλ₯Ό μ•Œμ•„λ³΄μž!

νš¨μœ¨μ„±μ΄ μ˜¬λΌκ°„λ‹€. (μž¬ν™œμš©μ΄ κ°€λŠ₯ν•˜κΈ° λ•Œλ¬Έμ—!)

 

function isDate(date: Date | string): date is Date {
    return date instanceof Date;
}

function getDate(date: Date | string): Date {
    if(isDate(date)) {
        return date;
    }

    return new Date(date);
}

 

 

End.

728x90
λ°˜μ‘ν˜•

+ Recent posts