๐ย Reference
๐ย Chapter
asserts๊ฐ ๋ถ์ ํจ์๋ ํน์ ์กฐ๊ฑด์ด ์ฐธ์์ ๋ณด์ฅํ๋ฉฐ, ๋ง์ฝ ๊ฑฐ์ง์ด๋ฉด ์์ธ๋ฅผ ๋์ ธ ํ๋ก๊ทธ๋จ ์คํ์ ์ค๋จ์ํจ๋ค.function assert(condition: any, msg?: string): asserts condition {
if (!condition) {
throw new AssertionError(msg);
}
}
: asserts condition์ "์ด ํจ์๊ฐ ์ ์์ ์ผ๋ก ๋ฆฌํด๋๋ค๋ฉด, ์ธ์๋ก ๋์ด์จ condition์ ๋ฌด์กฐ๊ฑด true๋ค"๋ผ๋ ๋ป์ด๋ค.if๋ฌธ๋ณด๋ค ์ข์๊น? (ํ์
์ขํ๊ธฐ)assert ํจ์ ์ดํ์ ์ฝ๋์์ ๋ณ์์ ํ์
์ ์๋์ผ๋ก ์ถ๋ก (Type Narrowing)ํด์ค๋ค.function processInput(input: string | null) {
// ์ ํ ์กฐ๊ฑด ๊ณ์ฝ: input์ ์ ๋ null์ผ ์ ์์
assert(input !== null, "์
๋ ฅ๊ฐ์ด null์
๋๋ค.");
// ์ฌ๊ธฐ์๋ถํฐ TypeScript๋ input์ด 'string'์์ 100% ํ์ ํฉ๋๋ค.
// ๋ณ๋์ null ์ฒดํฌ ์์ด ๋ฉ์๋๋ฅผ ํธ์ถํ ์ ์์ต๋๋ค.
console.log(input.toUpperCase());
}