It's safer to use non-null assertions over unnecessary type assertions in TypeScript, since type assertions are bivariant.
-ReactDOM.createRoot(document.getElementById('root') as HTMLElement))
+ReactDOM.createRoot(document.getElementById('root')!)
Here are some practical advantages of using non-null assertions to render React elements:
- Readability of using the right syntax to assert a non-null value
- Discouraging use of
aswhich many TypeScript beginners may not understand the dangers of - You won't get a type error if you render to an
Elementthat isn't anHTMLElement, such as<svg>/SVGSVGElement - You will get a type error if you render to a value that isn't always an
Element, such asElement | boolean