Type Guards and Differnetiating Types

TypeScript HandBook Linksarrow-up-right DEVarrow-up-right

A type guard is some expression that performs a runtime check that guarantees the type in some scope. νƒ€μž…μ΄ λ¬Έμžμ—¬λ„ 숫자λ₯Ό 써도 λ˜λŠ” 보μž₯을 ν•΄μ€€λ‹€.(?)

four main ways to use type guards

  • in keyword

  • typeof keyword

  • instanceof keyword

  • predicate

Using type predicates (parameterName is Type)

interface Cat {
  numberOfLives: number;
}

interface Dog {
  isAGoodBoy: boolean;
}

// Boolean 값을 returnν•˜λŠ”λ° 쒀더 μ •ν™•ν•˜κ²Œ animal is Cat 으둜 해쀄 수 μžˆλ‹€!
function isCat(animal: Cat | Dog): animal is Cat {
  return typeof animal.numberOfLives === 'number';
}

parameterName은 ν˜„μž¬ ν•¨μˆ˜ μ‹œκ·Έλ‹ˆμ²˜μ˜ 맀개 λ³€μˆ˜ 이름이어야 ν•œλ‹€.

이 κ°œλ…μ€ or(|)μΌλ•Œ 많이 μ“°μ΄λŠ”λ° 이 or이 λ³΅μž‘ν•˜λ‹€. μ΄λŸ΄λ•Œ νƒ€μž…μ„ μ„€μ •ν•΄ 쀄 수 μžˆλŠ”κ²Œ νƒ€μž…κ°€λ“œμ΄λ‹€.

Last updated