Home ๐ŸŒ€ 3/16 TS - DOM ํ•จ์ˆ˜ ํƒ€์ž… ์˜ค๋ฅ˜ ํ•ด๊ฒฐํ•˜๊ธฐ (ref. ts:2740)
Post
Cancel

๐ŸŒ€ 3/16 TS - DOM ํ•จ์ˆ˜ ํƒ€์ž… ์˜ค๋ฅ˜ ํ•ด๊ฒฐํ•˜๊ธฐ (ref. ts:2740)

DOM Element type

1
2
3
4
5
6
7
function $(selector: string) {
  return document.querySelector(selector);
}

const confirmedTotal = $(".confirmed-total");
const deathsTotal = $(".deaths");
const recoveredTotal = $(".recovered");

์œ„์™€ ๊ฐ™์€ util ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ–ˆ์„ ๋•Œ, ๋ฐ˜ํ™˜๋˜๋Š” ํƒ€์ž…์€ Element์ธ ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

querySelectyor๋กœ ๊ฐ€์ ธ์˜จ DOM Element์˜ ํƒ€์ž…์€ ์–ด๋–ป๊ฒŒ ๋ ๊นŒ?

ํƒ€์ž…์„ ๋‹จ์–ธํ•ด์ฃผ์ง€ ์•Š์œผ๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

1
deathsTotal.innerText = data[0].Cases; // error here(ts:2740)

Solution

DOM element์˜ ํƒ€์ž…์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด extend๋  ์ˆ˜ ์žˆ๋‹ค. ๋”ฐ๋ผ์„œ tag์˜ ์ข…๋ฅ˜์— ๋”ฐ๋ผ ์•„๋ž˜์™€ ๊ฐ™์ด type์„ ๋‹จ์–ธํ•ด์ฃผ๋ฉด ์—๋Ÿฌ๊ฐ€ ์—†์–ด์ง„๋‹ค.

1
2
3
4
5
6
7
8
9
10
11
12
// Dom Element์˜ type๋“ค
var DomElement: Element | HTMLElement | HTMLParagraphElement;

// wrong solution - ํƒ€์ž… ๊ฐ„์— ํ˜ธํ™˜ ํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ์—ฌ์ „ํžˆ ์—๋Ÿฌ
const confirmedTotal: HTMLSpanElement = $(".confirmed-total"); //<span>
const deathsTotal: HTMLParagraphElement = $(".deaths"); //<p>
const recoveredTotal: HTMLParagraphElement = $(".recovered"); //<p>

// correct solution
const confirmedTotal = $(".confirmed-total") as HTMLSpanElement; //<span>
const deathsTotal = $(".deaths") as HTMLParagraphElement; //<p>
const recoveredTotal = $(".recovered") as HTMLParagraphElement; //<p>

๋˜ํ•œ ์•ž์œผ๋กœ as๋ฅผ ์ด์šฉํ•ด type ๋‹จ์–ธ ํ•ด์ฃผ๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ์•„์ง€๋ฉด utilํ•จ์ˆ˜๋กœ ์ € ๋ถ€๋ถ„์„ ๋นผ์„œ ์ฝ”๋“œ๋ฅผ ๋” ๊น”๋”ํ•˜๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

TS๊ฐ•์˜๋ฅผ ๋“ค์œผ๋ฉฐ ์ •๋ฆฌํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค.

This post is licensed under CC BY 4.0 by the author.

โ˜€๏ธ[๋ชจ๋˜] Ch-27. Javascript ๋ฐฐ์—ด - (1) ๊ฐœ๋… ๋ฐ ๊ธฐ๋ณธ ๋ฉ”์„œ๋“œ

๐ŸŒ€ Event, Axios type ์ •์˜