Prerequisite
tsconfig.json
1
"strict": true

์๋ฐ family option๋ค ๋ชจ๋์ ๋ํด ๊ฐํ ํ์ ์ฒดํฌ๋ฅผ ํด์ฃผ๋ ์ต์ ์ด๋ค.
1. Null ํ์ ์ค๋ฅ ๋ฐ ํจ์ ํ์ ์ค๋ฅ ํด๊ฒฐ
Strict Null Check
1
2
3
function initEvents() {
rankList.addEventListener('click', handleListClick);
}
rankList์ ๋ํ null check๊ฐ ํ์ํ๋ค. ๋ฐ๋ผ์ initEvents ํจ์ ์ต์๋จ์ ๋ค์๊ณผ ๊ฐ์ Null check๋ฅผ ๋ฃ์ด์ค์ผ๋ก์จ ํด๊ฒฐํ๋ค.
1
2
3
if (!rankList) {
return;
}
Strict Function Type Check
function์ argument type์ ๋ํด์๋ ์ ํํ๊ฒ ๋ง์ถฐ์ฃผ์ด์ผ ํ๋ค. ๋ฌผ๋ก tsconfig.json์์ โstrictFunctionTypes:falseโ๋ฅผ ํ๋ฉฐ ์๋ฌ๊ฐ ์ฌ๋ผ์ง๊ธด ํ๋ค.
์๋ฅผ ๋ค์ด handleClick์ด๋ ํจ์๊ฐ ์๊ณ , ์ด๊ฑธ something์ addEventListener๋ก ์ถ๊ฐํ๋ ค๊ณ ํ ๋ ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ค.
1
2
3
4
5
something.addEventListener('click', handleClick)
async function handleClick(event: MouseEvent) {
//...
}
์๋ฌ ๋ฉ์์ง๋ฅผ ์ฐจ๊ทผ์ฐจ๊ทผ ์ฝ์ด๋ณด๋ฉด ๋งจ ๋์ ์ด๋ฐ ๋ฌธ๊ตฌ๋ฅผ ํ์ธํ ์ ์๋๋ฐ

event์ Type์ด MouseClick์ธ๋ฐ addEventListener์ ์ฝ๋ฐฑ์ ํ๋ผ๋ฏธํฐ ํ์ ์ด๋ ํธํ์ด ๋ถ๊ฐ๋ฅํด์ ๊ทธ๋ ๋จ๋ค. ํ์ ์ MouseEvent โ Event๋ก ๋ฐ๊ฟ์ฃผ๋ฉด ๋๋ค.
์ฌ๊ธฐ์ ๋ฐฐ์ด์ : ๊ตฌ๊ธ๋ง์ ์ ํ๊ธฐ ์ ์ ์๋ฌ ๋ฉ์ธ์ง๋ฅผ ์ ํ์ธํ์. ๊ตฌ๊ธ๋ง์ ์ง์ ๋์ผ ์ ์๋ค.
2. แแ กแแ ตแธแแ ณแแ ณแ แ ตแธแแ ณ แแ ขแแ กแผ แแ กแแ ตแธแแ ด แแ ฑแแ จ แแ ฎแแ ฉ
DOM Element ํ์ ํธํ ๊ด๋ จํด์ ์๊ณ ์์ผ๋ฉด ์ ์ฉํ ๊ฒ ๊ฐ๋ค.
1
2
3
4
5
6
7
8
// hierarchy: a > b > c ์์ผ๋ก ๋๋ค.
const a: Element;
const b: HTMLElement;
const c: HTMLDivElement;
// hierarchy: ev1 > ev2 > ev3 ์์ผ๋ก ๋๋ค.
const ev1: Event;
const ev2: UIEvent;
const ev3: MouseEvent;
3. ํ์ ๋จ์ธ์ ์ด์ฉํ ํ์ ์๋ฌ ํด๊ฒฐ
1
recoveredList!.appendChild(li);
recoveredList ์ค๋ธ์ ํธ๊ฐ possibly null์ผ ์ ์๊ธฐ ๋๋ฌธ์ ์๋ฌ๊ฐ ๋ํ๋๋๋ฐ ์ด๋ โ!โ๋ฅผ ๋ค์ ๋ถ์ฌ์ non-null์์ ๋ช
์ํด ํด๊ฒฐํด๋ณผ ์ ์๋ค.
์ด๋ฐ ํ์
๋จ์ธ ์ ์ฃผ์์ ์ด ์๋๋ฐ
1
2
3
4
5
6
7
8
9
10
11
12
13
interface Food{
type: string;
price: number;
}
// type annotation
const sushi: Food = {
type: Japanese;
price: 18000;
}
// type assertion
const chicken = {} as Food;
ํ์ ๋จ์ธ์ ๊ฒฝ์ฐ ํ์ ์๋ฌ๊ฐ ๋จ์ง๋ ์์ง๋ง ์ดํ์ ์ด๊ธฐ๊ฐ์ ์ ํ์ง ์์์ผ๋ก์จ ๋ฐ์ํ๋ ์ค๋ฅ์ ์์ธ์ด ๋ ์ ์๋ค.
4. ์ต์ ๋ ์ฒด์ด๋ ์ฐ์ฐ์
1๋ฒ์์์ฒ๋ผ possible null ํ์ ์ ๋ํด ๋งค๋ฒ ์ฒดํฌํด์ค๋ ๋์ง๋ง ๋ฒ๊ฑฐ๋ก์ฐ๋ฏ๋ก ๋ค์๊ณผ ๊ฐ์ด optional chainig์ ์ฐ๋ฉด ๋ ๊ฐ๊ฒฐํ๋ค.
1
recoveredList?.appendChild(li);
5. DOM ์ ํธ ํจ์ ํ์ฉ์ฑ์ ๋์ด๋ ํ์ ์ ์
์ด์ ๊น์ง๋ ์ ํธํจ์๋ฅผ ์๋์ ๊ฐ์ด ์ ์ ํด ์ฌ์ฉํ๊ณ ์์๋ค.
1
2
3
4
5
6
//util
function $(selector: string) {
return document.querySelector(selector);
}
// DOM
const confirmedTotal = $('.confirmed-total') as HTMLSpanElement;
์๋์ ๊ฐ์ด ์์ ํ๋ฉด ๋ ๊ฐ๊ฒฐํด์ง ์ ์๊ณ , ๋ํดํธ๊ฐ์ ์ ์ํจ์ผ๋ก์จ ๋ ๋น ๋ฅธ ๊ฐ๊ฒฐํ ํ์ ์ถ๋ก ์ด ๊ฐ๋ฅํ๋ค.
1
2
3
4
5
6
7
//util - using generic
function $<T extends HTMLElement = HTMLDivElement>(selector: string) {
const element = document.querySelector(selector);
return element as T; // ๋ฆฌํด ํ์
์์ Null ์์ ๊ธฐ
}
// DOM
const confirmedTotal = $<HTMLSpanElement>('.confirmed-total');
๊ฐ์ ๋!
reference.
https://www.typescriptlang.org/tsconfig#strict
TS๊ฐ์๋ฅผ ๋ค์ผ๋ฉฐ ์ ๋ฆฌํ ๋ด์ฉ์ ๋๋ค.