Type Guards and Differnetiating Types

TypeScript HandBook Links DEV

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

Was this helpful?