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

Created on 24 Oct 2019  ·  1Comment  ·  Source: microsoft/TypeScript

TypeScript Version: 3.6.4

Code

document.querySelector('.page').offsetTop
Working as Intended

Most helpful comment

This is correct. First of all, the result can be null, so if you have strictNullChecks enabled you need to perform a null check first:

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

Secondly, the return type is Element, and Element has no property offsetTop. You likely expect it to return a HTMLElement, but this is not obvious to the compiler because it could just as well be a SVGElement.

To fix this you can either use a type-assertion: element as HTMLElement

Or actively perform a runtime check: if (element instanceof HTMLElement) {}


Everything works as it should. Please also take note of the issue template.

>All comments

This is correct. First of all, the result can be null, so if you have strictNullChecks enabled you need to perform a null check first:

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

Secondly, the return type is Element, and Element has no property offsetTop. You likely expect it to return a HTMLElement, but this is not obvious to the compiler because it could just as well be a SVGElement.

To fix this you can either use a type-assertion: element as HTMLElement

Or actively perform a runtime check: if (element instanceof HTMLElement) {}


Everything works as it should. Please also take note of the issue template.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

uber5001 picture uber5001  ·  3Comments

Roam-Cooper picture Roam-Cooper  ·  3Comments

wmaurer picture wmaurer  ·  3Comments

fwanicka picture fwanicka  ·  3Comments

manekinekko picture manekinekko  ·  3Comments