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
as
which many TypeScript beginners may not understand the dangers of - You won't get a type error if you render to an
Element
that 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