4 ms·
Hmm, not sure what you're saying exactly. Null and undefined are different. A common example would be any sort of patch operation - setting a value to null is v
by dvdhnt 6y ago
Hmm, not sure what you're saying exactly. Null and undefined are different. A common example would be any sort of patch operation - setting a value to null is valid, whereas if the value of that property is undefined, it likely should be ignored.
Sorry if I am misunderstanding your statement.
- srcreigh 6y agoA 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.
- rfw300 6y agoI think what he’s saying is not that there is no semantic difference between the two, but that in practice programmers use the two so interchangeably that not checking for both is likely to cause more trouble than it’s worth.