์กฐ๊ฑด๋ฌธ์—์„œ ๊ฐ์ฒด์˜ ํƒ€์ž…์„ ์ขํ˜€๊ฐ€๋ฉด์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ

`typeof

function doSomething(x: number | string) {
	if(typeof x === "string") {
		console.log(x.slice(0,1)); // x ๋Š” string์ด๋ผ๋Š” ๋ณด์žฅ์ด ์žˆ์Œ
	}
}

instanceof

function doSomething(x: Foo | Bar) {
	if(x instanceof Foo) {
		console.log(x.foo); // x ๋Š” Foo์ด๋ผ๋Š” ๋ณด์žฅ์ด ์žˆ์Œ
	}
}
 

in

interface A {
  x: number;
}
interface B {
  y: string;
}
 
function doStuff(q: A | B) {
  if ('x' in q) {
  // q: A
  }
  else {
  // q: B
  }
}

๋ฆฌํ„ฐ๋Ÿด Type Guard

type Foo = {
  kind: 'foo', // ๋ฆฌํ„ฐ๋Ÿด ํƒ€์ž…
  foo: number
}
type Bar = {
  kind: 'bar', // ๋ฆฌํ„ฐ๋Ÿด ํƒ€์ž…
  bar: number
}
 
function doStuff(arg: Foo | Bar) {
  if (arg.kind === 'foo') {
	  console.log(arg.foo); // ใ…‡ใ…‹
	  console.log(arg.bar); // Error!
  }
  else {  // ๋ฐฑํผ Bar๊ฒ ๊ตฐ.
	  console.log(arg.foo); // Error!
	  console.log(arg.bar); // ใ…‡ใ…‹
  }
}

null, undefined

==, != ์œผ๋กœ null, undefined๋ฅผ ํ•œ๋ฒˆ์— ๊ฑธ๋Ÿฌ๋‚ผ ์ˆ˜ ์žˆ๋‹ค

function foo(a?: number | null) {
  if (a == null) return;
  // ์ด์ œ๋ถ€ํ„ฐ a๋Š” ๋ฌด์กฐ๊ฑด number์ž…๋‹ˆ๋‹ค.
}

์‚ฌ์šฉ์ž ์ •์˜ type guard ํ•จ์ˆ˜

type guard ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ํŠน์ • ์ธ์ž์˜ ํƒ€์ž…์„ ๊ฒฐ์ • ์ง€์–ด์ค„ ์ˆ˜ ์žˆ๋‹ค

function isFoo(arg: any): arg is Foo {
  return arg.foo !== undefined;
}

Type guard ์™€ Callback

์ฝœ๋ฐฑ ํ•จ์ˆ˜ ๋‚ด์—์„œ type guard๊ฐ€ ํ’€๋ฆฌ๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค.

// Example Setup
declare var foo:{bar?: {baz: string}};
function immediate(callback: () => void) {
  callback();
}
 
// Type Guard
if (foo.bar) {
  console.log(foo.bar.baz); // ใ…‡ใ…‹
  functionDoingSomeStuff(() => {
    console.log(foo.bar.baz); // TS error: ํ•ด๋‹น ๊ฐ์ฒด๋Š” 'undefined'์ผ ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ์Šต๋‹ˆ๋‹ค.
  });
}

์ด๋Ÿฌํ•œ ๊ฒฝ์šฐ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋กœ์ปฌ ๋ณ€์ˆ˜์—๋‹ค๊ฐ€ ๊ฐ’์„ ๋‹ด์•„ ํ•ด๊ฒฐ ํ•  ์ˆ˜ ์žˆ๋‹ค

// Type Guard
if (foo.bar) {
  console.log(foo.bar.baz); // ใ…‡ใ…‹
  const bar = foo.bar;
  functionDoingSomeStuff(() => {
  console.log(bar.baz); // ใ…‡ใ…‹
  });
}

์ฐธ๊ณ