Replies: 1 comment
-
This is a great question! I don’t think that What does make for an interesting question and analysis, though, is the addition of the optional chaining For my own part, I still like import { mapOr, just } from 'true-myth/maybe';
const add1 = (a: number) => a + 1;
function withMaybe(maybe: Maybe<number>): number {
return maybe.mapOr(0, add1);
}
function withOptional(optional: number | null): number {
return optional ? add1(optional) : 0;
} This is a toy example, of course, but it shows how the new operators don't help you at all with standalone functions. Notice that there’s no good way to use optional chaining or nullish coalescing here! The operators are biased toward optional object types with methods, and really hurt when you're working with primitives or want to apply functions to objects as arguments (rather than just methods). And that’s totally fine; the point is simply that That said, in the cases where optional chaining or nullish coalescing are applicable, they’re much nicer: function withMaybe(maybe: Maybe<string>) {
return maybe.mapOr(0, (s) => s.length));
}
function withOptional(optional: string | null) {
return optional?.length ?? 0;
} So: it depends on what you’re doing. Both work. |
Beta Was this translation helpful? Give feedback.
-
Is there a good case for using the
Maybe
type over enabling strictNullChecks in typescript? This flag will require you to handle null and undefined as separate types from the type of your value.Beta Was this translation helpful? Give feedback.
All reactions