4 ms·
I would like a null conditional operator and null coalescing operator. return data?.error?.message ?? "no error"; Also pattern matching would be a big win.
by PretzelFisch 8y ago
I would like a null conditional operator and null coalescing operator.
return data?.error?.message ?? "no error";
Also pattern matching would be a big win.
- Forge36 8y agoNull coalescing is already possible with ||. Though I'd like ?? If it worked for undefined coalescing as well.
- untog 8y agoYou still have to be more verbose, though. You can't do obj1?.obj2 with ||, not could you do obj1?.method()
- coldtea 8y agoHow does || differentiate null from e.g. 0 or ""?
- GordonS 8y agoIt doesn't - it tests for a "truthy" value.
- charrondev 8y agoThese are not the same. let val = 0 val || 30 // 30 val ?? 30 // 0 The same goes for other falsy values.
- untog 8y agoAbsolutely this. I've done work in both Swift and JS (well, Typescript) and every feature on my wishlist is from Swift. Null operator like you suggest, guard statements and structs, which are the best equivalent to value-type objects as outlined in the article.
- kangax 8y agoYep. Both are stage-1 proposals: https://github.com/tc39/proposal-optional-chaining https://github.com/tc39/proposal-optional-chaining https://github.com/tc39/proposal-nullish-coalescing https://github.com/tc39/proposal-nullish-coalescing Recently started using optional chaining in our codebase (via Babel 7) and it's great so far. Also gives us proper static typing safety unlike Lodash `get(...)`