Skip to content

πŸ“• 10μ›” 27일 슀크럼 기둝

Chun Hwa Park edited this page Oct 27, 2021 · 2 revisions

Typescript 곡뢀 ν›„ λŠλ‚€μ 

νƒ€μž…μŠ€ν¬λ¦½νŠΈ ν•Έλ“œλΆμœΌλ‘œ 각자 κ³΅λΆ€ν•œ λ’€(ν•¨μˆ˜, λ¦¬ν„°λŸ΄ νƒ€μž…, μœ λ‹ˆμ–Έκ³Ό ꡐ차 νƒ€μž…), λŠλ‚€ 점을 곡유

νƒ€μž…μŠ€ν¬λ¦½νŠΈ

TypeScript ν•œκΈ€ λ¬Έμ„œ

  • ν•¨μˆ˜, λ¦¬ν„°λŸ΄ νƒ€μž…, μœ λ‹ˆμ–Έκ³Ό κ΅μ°¨νƒ€μž…μ€ κ³΅λΆ€ν• λ§Œ ν–ˆλ‹€.
  • μΈν„°νŽ˜μ΄μŠ€κ°€ 더 μ–΄λ €μ› λ‹€.

νƒ€μž…μŠ€ν¬λ¦½νŠΈ REPL

TS Playground - An online editor for exploring TypeScript and JavaScript

Union

interface Fish {
    swim(): void;
    layEggs(): void;
}

interface Bird {
    fly(): void;
    layEggs(): void;
}

const fish: Fish = {
    swim() {
        console.log('swim');
    },
    layEggs() {
        console.log('layEggs');
    }
};

const bird: Bird = {
    fly() {
        console.log('fly');
    },
    layEggs() {
        console.log('layEggs');
    }
};

function getPet(): Fish | Bird {
    return [fish, bird][Math.random()*2];
}

const pet = getPet();
pet.layEggs();  // 곡톡 속성이기 λ•Œλ¬Έμ— λ°”λ‘œ μ‚¬μš©κ°€λŠ₯

(pet as Bird).fly();   // μΊμŠ€νŒ…μ„ ν•΄μ•Ό μ‚¬μš©κ°€λŠ₯
(pet as Fish).swim();  // μ–΄λ””μ—μ„œ 였λ₯˜κ°€ λ°œμƒν• μ§€ λͺ¨λ₯Έλ‹€ -> BAD

Interface vs Type

  • InterfaceλŠ” μ„ μ–Έ 병합이 κ°€λŠ₯ν•˜μ§€λ§Œ Type은 그렇지 μ•Šλ‹€.(μ„ μ–Έ λ³‘ν•©μ΄λž€
interface Window {
  title: string;
}
interface Window {
  ts: import("typescript");
}

이런 μ‹μœΌλ‘œ μ„ μ–Έν•˜λ©΄ 컴파일 μ‹œμ μ— 합쳐져 Windowκ°€ titleκ³Ό ts속성을 λͺ¨λ‘ κ°€μ§€κ²Œ λœλ‹€.)

Type vs Interface, μ–Έμ œ μ–΄λ–»κ²Œ?

Clone this wiki locally