4 ms·
null checking can have some surprising results. The standard React pattern: ReactDOM.render( <Start />, document.getElementById("conten
by technion 10y ago
null checking can have some surprising results. The standard React pattern:
ReactDOM.render(
<Start />,
document.getElementById("content")
);
Will error because getElementById can return null. And it's 100% valid and imo 100% worth checking for - but I can't say I've ever heard of anyone doing it before Typescript suggested it.
- Ycros 10y ago2.0 added an exclamation mark (!) postfix operator that asserts a type as being non-null/non-undefined. So these checks are easy to explicitly ignore.
- technion 10y agoThanks! I wasn't aware of that. That said, I don't actually want to ignore it - I think it's good that Typescript is showing people some potentially errors they never thought to look for. This pattern really isn't hard and if it saves you from one "undefined is undefined" then it was worth it. const item = document.getElementById("content"); if (item == null) { console.log("Render container missing");
- mercer 10y agoCould you (or someone else) help me out here? I'd rather like getting an error in this situation, but in my code, with strictNullChecks turned on, TypeScript seems to be fine with the above... What am I missing?
- technion 10y agoUnfortunately all I've got here is that the behaviour can be seen in my boilerplate React app: https://github.com/technion/awesome-sec-audit/blob/master/assets/awesome-sec-audit-run.tsx https://github.com/technion/awesome-sec-audit/blob/master/as... If you insert the element directly in line 25 you'll get: error TS2345: Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element'.
- mercer 10y agoStrange. On my end it does look like ReactDOM's 'render' method actually accepts HTMLElement | null, and therefore doesn't throw an error.