Home > Enterprise >  Dynamically assign a variable depending on window and DOM-element in TypeScript
Dynamically assign a variable depending on window and DOM-element in TypeScript

Time:09-26

I want assign a variable depending on the DOM-element or window

const layoutContainer = document.querySelector('[data-test-element="layout"]') ?? window
let pageScrollOffsetY = layoutContainer.scrollTop ?? window.pageYOffset

but property scrollTop exists only in DOM-element and I getting this error: TS2551: Property 'scrollTop' does not exist on type 'Element | (Window & typeof globalThis)'. Did you mean 'scrollTo'?   Property 'scrollTop' does not exist on type 'Window & typeof globalThis'

CodePudding user response:

You should probably rewrite it like this:

const pageScrollOffsetY = document
  .querySelector('[data-test-element="layout"]')?.scrollTop 
  ?? window.pageYOffset

Otherwise, layoutContainer might be a window if document.querySelector('[data-test-element="layout"]') is nullish. And a windows does not have a scrollTop property leading to a runtime error.


const layoutContainer = document.querySelector('[data-test-element="layout"]') ?? window
let pageScrollOffsetY = (layoutContainer as Element)?.scrollTop ?? window.pageYOffset
  • Related