0

I have an TypeScript app where I have function that selects html element, and another function that modifies that element. This far, I have done it like this:

const modifyElement(element:any):void => {
 // do stuff to element
}
// call the function
modifyElement(document.querySelector("#id"))

ButI don't like doing it with type any, so what is the type I should give to it? ( or is this whole concept of passing HTML elements invalid TypeScript)

  • The parameter type would be `Element | null`. But `querySelector` takes a generic type parameter, so if you know that the element with that ID is an `input` (for instance), you could use `HTMLInputElement | null`. TypeScript will infer `HTMLInputElement` as the type argument for `querySelector`. – T.J. Crowder Jan 09 '21 at 13:22
  • Thanks! But that gives me the problem that the argument with type Element | null, TypeScript throws error 'Object is possibly null' – Otso Kurkela Jan 09 '21 at 13:39
  • That's because it's true, `querySelector` can return `null`. You need a guard handling that. (Or a non-null type assertion, but type assertions are generally poor practice because they often end up being wrong.) – T.J. Crowder Jan 09 '21 at 13:55

0 Answers0