์กฐ๊ฑด๋ฌธ์์ ๊ฐ์ฒด์ ํ์ ์ ์ขํ๊ฐ๋ฉด์ ์ฌ์ฉํ๋ ๊ฒ
`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); // ใ
ใ
});
}