4 ms·
A concrete example of this is setState in React. T | null signifies that it can be cleared by using setState({prop: null}). T | undefined means that it may st
by srcreigh 6y ago
A concrete example of this is setState in React.
T | null signifies that it can be cleared by using setState({prop: null}).
T | undefined means that it may start out undefined, but if it becomes defined it'll probably stay that way. If you try doing setState({prop: undefined}), it won't work.
- recursive 6y agoThere doesn't seem to be any fundamental reason why that had to be the case. I'm not a react expert, but it seems like it would have been more obvious to me if null and undefined were treated the same. The distinction should be whether the key exists in the object.
- presentation 6y agoIt's a poor design carried over from legacy JavaScript, but there are clear differences at the language level. While not the only one, the biggest one to me is this kind of code: const x = {}; x.foo // returns undefined const y = { foo: undefined }; y.foo // also undefined Basically a member not being provided will return undefined, whereas `null` had to actually be set. Hence I think the tendency for checking for the absence of something via `undefined`, while expressing the deletion of something with `null`. Sure, you can assert more specific types in TypeScript to step around that, or you can do something less intuitive like checking for `keyof` to detect absence; but this is both straightforward and presents less issues when interfacing with inputs from non-typescript-using users.