Programming/TypeScript

[TypeScript] Property 'offsetTop' does not exist on type 'Element'.ts(2339) ์˜ค๋ฅ˜

yuri lee 2022. 11. 7. 21:42
๋ฐ˜์‘ํ˜•

Intro

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‚ฌ์šฉํ•˜๋˜ ๋„์ค‘ ์•„๋ž˜์™€ ๊ฐ™์€ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค. 

 

Property 'offsetTop' does not exist on type 'Element'.ts(2339)

 

Why?

document.querySelector('.page').offsetTop

๋‹ค์Œ์˜ ์ฝ”๋“œ๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ด…์‹œ๋‹ค. ์ด ์ฝ”๋“œ๋Š” ๋งž๋Š” ์ฝ”๋“œ์ด์ง€๋งŒ, ๊ฒฐ๊ณผ๊ฐ’์ด null์ด ๋  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ null ์ฒดํฌ๋ฅผ ํ•ด์ค˜์•ผ ํ•ฉ๋‹ˆ๋‹ค. 

 

๋‘๋ฒˆ์งธ๋กœ๋Š”, ํ˜„์žฌ ๋ฆฌํ„ด ํƒ€์ž…์€ Element์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ Element๋Š” offsetTop์ด๋ผ๋Š” ํ”„๋กœํผํ‹ฐ๋ฅผ ๊ฐ–๊ณ  ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค. HtmlElement๋กœ ๋ฐ˜ํ™˜๋  ๊ฒƒ์ด๋ผ๊ณ  ์˜ˆ์ƒํ•  ์ˆœ ์žˆ์ง€๋งŒ, SVGElement๊ฐ€ ๋  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ปดํŒŒ์ผ๋Ÿฌ์—๊ฒŒ๋Š” ์ด ์ •๋ณด๊ฐ€ ์ •ํ™•ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์ด ๋ถ€๋ถ„ ์—ญ์‹œ type-assertion์„ ํ†ตํ•ด ์ˆ˜์ •ํ•ด์ค˜์•ผ ํ•ฉ๋‹ˆ๋‹ค. ํ˜น์€ ๋Ÿฐํƒ€์ž„ ์ค‘ ์ฒดํฌ๋ฅผ ํ•˜์…”๋„ ๋ฉ๋‹ˆ๋‹ค. 

How to solve the problem

null-check

const element = document.querySelector('.page');
if (element !== null) { ... }

type-assertion

element as HTMLElement

runtime-check

if (element instanceof HTMLElement) {}

https://github.com/microsoft/TypeScript/issues/34694

๋ฐ˜์‘ํ˜•