Type Guards and Differnetiating Types
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
keywordtypeof
keywordinstanceof
keywordpredicate
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?