I’m late to TypeScript, so I’m converting some legacy code to help me learn about it. I’ve come across a few situations that benefit from further investigation.
One of them is when querySelector results in typescript issues.
const el = document.querySelector("#craftweight"); el.innerHTML = num; // ^^ Object is possibly 'null'.
One possible way to deal with that is to use explicit typecasting to say that el is an HTMLElement
const el = document.querySelector("#craftweight") as HTMLElement; el.innerHTML = num;
Which fixes the problem, but we’re told at Clean DOM Queries that a much cleaner solution is to use a type-argument instead:
The trouble is that we’re left with the same possible null issue:
const el = document.querySelector<HTMLElement>("#craftweight"); el.innerHTML = num; // ^^ Object is possibly 'null'.
Others recommend casting all of it:
But TypeScript hates that:
const el = <HTMLElement>document.querySelector("#craftweight"); // Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead. el.innerHTML = num;
And we go back around in circles to explicit typecasting instead.
Does TypeScript have an official best-practice in this regard?
Or failing that, what do you think is the best TypeScript solution for this situation?