| Type Assertion!

TypeScript์˜ ํƒ€์ž… ํ‘œ๋ช…์€ ํ”„๋กœ๊ทธ๋ž˜๋จธ๊ฐ€ ์ปดํŒŒ์ผ๋Ÿฌ์—๊ฒŒ โ€œ๋‚ด๊ฐ€ ๋„ˆ๋ณด๋‹ค ํƒ€์ž…์— ๋” ์ž˜ ์•Œ๊ณ  ์žˆ๊ณ , ๋‚˜์˜ ์ฃผ์žฅ์— ๋Œ€ํ•ด ์˜์‹ฌํ•˜์ง€ ๋งˆ๋ผโ€ ๊ณ  ํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™๋‹ค

Type Assertion: ํƒ€์ž…์„ ๊ฐ•์š”ํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ์— ์‚ฌ์šฉ?? ๋‹จ, ์ง€์–‘ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค. ๐Ÿ’ฉ


โœ”๏ธ Type Assertion ์˜ˆ์ œ1

function jsStrFunc(): any {
  return "hello";
}
const result = jsStrFunc();
console.log((result as string).length); // (1)
console.log((<string>result).length);

(1) result as string: result๋Š” string์ด์•ผ!! string์ž„์„ ํ™•์ธํ•˜๊ธฐ ๋•Œ๋ฌธ์— string method๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค


โœ”๏ธ Type Assertion๋ฅผ ์ง€์–‘ํ•ด์•ผ ํ•˜๋Š”์ด์œ ! ์˜ˆ์ œ2

function jsStrFunc(): any {
  return 2; // (2) ๐Ÿ˜ฑ์•„๋ž˜์—์„œ ๋ฌธ์ž์—ด์ž„์—๋„ ์ˆซ์ž๋ฅผ ์ง€์ •ํ•  ๊ฒฝ์šฐ์—๋„ ์—๋Ÿฌ๋Š” ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค;;
}
const result = jsStrFunc();
console.log((result as string).length); // (3)
console.log((<string>result).length); // ์œ„์˜ as์™€ ๊ฐ™์€ ๋ฌธ๋ฒ•

(3) ๐Ÿ˜ฑ๐Ÿ˜ฑ as๋ฅผ ๋ถ™ํ˜€ ํƒ€์ž…์„ ์žฅ๋‹ดํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ์ปดํŒŒ์ผ ์—๋Ÿฌ๋Š” ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค;; ๋‹ค๋งŒ ์‹คํ–‰ํ•  ๊ฒฝ์šฐ undefined๊ฐ€ ์ถœ๋ ฅ๋œ๋‹ค.


โœ”๏ธ Type Assertion ์˜ˆ์ œ3: Type Assertion์„ ์ง€์–‘ํ•ด์•ผ ํ•˜๋Š” ์ด์œ !! ๐Ÿ˜ฑ

const wrong: any = 5;
console.log((wrong as Array<number>).push(1)); // ๐Ÿ˜ฑ

์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ์ฃฝ์–ด๋ฒ„๋ ธ์–ด!!! ๐Ÿ˜ฑ๐Ÿ˜ฑ๐Ÿ˜ฑ๐Ÿ˜ฑ๐Ÿ˜ฑ๐Ÿ˜ฑ


โœ”๏ธ Type Assertion ์˜ˆ์ œ4: !๋ฅผ ๋ถ™ํžˆ๋ฉด ํ™•์‹ ํ•ด

function findNumbers(): number[] | undefined {
  return undefined;
}
const numbers = findNumbers()!;
numbers.push(2); // ๐Ÿ˜ฑ numbers๋Š” number[]์ผ์ˆ˜๋„ ์žˆ๊ณ ,
// undefined ์ผ์ˆ˜๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—
// push()๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ ์—๋Ÿฌ ๋ฐœ์ƒ.

๐Ÿ“Œ !๋ฅผ ๋ถ™ํžˆ๋ฉด ํ™•์‹ ํ•ด๋ฅผ ํ‘œํ˜„. ์ฆ‰, numbers๋Š” ๋ฐฐ์—ด์ž„์„ ํ™•์‹ ํ•˜๋ฏ€๋กœ push๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์–ด! ์ฐธ๊ณ ๋กœ as๋Š” ์žฅ๋‹ดํ•ด!๋ฅผ ํ‘œํ˜„.


โœ”๏ธ Type Assertion ์˜ˆ์ œ5

const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;

const button = document.querySelector("class")!;