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๊ฐ์๋ฅผ ๋ค์ผ๋ฉฐ ์ ๋ฆฌํ ๋ด์ฉ์ ๋๋ค.