๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
IT-Engineering/TroubleShooting

React ๊ฐœ๋ฐœ์‹œ index.tsx์—์„œ Error ๋ฐœ์ƒ ํ•ด๊ฒฐ(TypeScript์‚ฌ์šฉ)

by ๐Ÿงž‍โ™‚๏ธ 2022. 5. 4.
๋ฐ˜์‘ํ˜•

React์—์„œ typescript๋กœ ๊ฐœ๋ฐœํ•˜๋Š”๋ฐ ์•„๋ž˜์˜ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.

const root = ReactDOM.createRoot(document.getElementById("root"));

 

์—๋Ÿฌ ๋‚ด์šฉ์€ ์•„๋ž˜์™€ ๊ฐ™์•˜๋‹ค.

Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'.
  Type 'null' is not assignable to type 'Element | DocumentFragment'.

Visual Studio Code์—์„œ ์—๋Ÿฌ๋ฅผ ๋ณด์ด๊ณ  ์žˆ๋Š” ํ™”๋ฉด

 

ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์€ ๊ฐ„๋‹จํ–ˆ๋‹ค. getElementById๋ฅผ ํ†ตํ•ด ๋ฐ›์•„์˜ค๋Š” ๊ฐ์ฒด์˜ Type์„ ์ง€์ •ํ•ด์ฃผ๋ฉด ๋œ๋‹ค. TypeScript๊ฐ€ ๋ฐ์ดํ„ฐ ํƒ€์ž…์„ ์•Œ์•„๋ณผ ์ˆ˜ ์žˆ๋„๋ก ํ•ด์ฃผ๋Š” ๊ฒƒ. ์ˆ˜์ •๋œ ์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๊ณ , ํ•ต์‹ฌ์€ as HTMLElement ๋‹ค.

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);

 

๋‹ค์Œ ๊ฐœ๋ฐœ์„ ํ•˜๋Ÿฌ ๋‹ค์‹œ ๋Œ์•„๊ฐ€๋ณด๊ฒ ๋‹ค. ๊ทธ๋Ÿผ 20000

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€