Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
Defining HTML Elements in typescript

I am trying to figure out what is the best way to define HTML elements in typescript. I keep running into the following issue.

If i grab an array of dom nodes with document.querySelectorAll then the type will be Element. But if I set the type to Element and I want to set the style attribute then I get the following error

Property 'style' does not exist on type 'Element'.

But if I set the type to HTMLElement then I get the following error

Argument of type 'Element' is not assignable to parameter of type 'HTMLElement'. Type 'Element' is missing the following properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and 111 more.

Here is a very simple example code:

type El = HTMLElement

const boxes = document.querySelectorAll('.box')

const setStyle = (el: El) => {
  el.style.background = 'green'
}

boxes.forEach(box => {
  setStyle(box)
})

So what is the correct way to go about handling this? I could just do something like:

boxes.forEach(box => {
  setStyle(box as HTMLElement)
})

but it seems counter productive to constantly do this.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You would need to cast the boxes as follow:

const boxes = document.querySelectorAll('.box') as NodeListOf<HTMLElement>

This way the elements of boxes would be considered as HTMLElement, fixing the issue.

about 4 years ago · Juan Pablo Isaza Report

0

Expanding on Ashok's answer. Write a function that will return your elements. e.g.

const getElements = (selector: string) => {
    return document.querySelectorAll(selector) as NodeListOf<HTMLElement>; 
}
about 4 years ago · Juan Pablo Isaza Report

0

The typed-query-selector package can infer the correct type in quite a few cases. Though the query '.box' won't contain enough information, using 'div.box' for example will make the code below type check without assertions:

import 'typed-query-selector'

type El = HTMLElement

const boxes = document.querySelectorAll('div.box')
// type: NodeListOf<HTMLDivElement>

const setStyle = (el: El) => {
  el.style.background = 'green'
}

boxes.forEach(box => {
  setStyle(box)
})

TypeScript playground

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!