Often in programming, we encounter methods where one or more parameters can be null
or undefined
(sometimes both with derived types). This can result in long method signatures like this:
doThing(
user: User | undefined | null,
thing: Thing | undefined | null,
...moreArgs
): Result {
// ...
}
I'm familiar with a few approaches to address this issue, but each has its drawbacks.
Optional parameters work well for truly optional arguments, but can feel odd when dealing with objects that may be null
.
While shorter, this syntax appears off to me:
doThing(user?: User | null, thing?: Thing | null, ...moreArgs)
Another method I know is using generics:
type Nullable<T> = T | null | undefined
doThing(user: Nullable<User>, thing: Nullable<Thing>)
This approach is reasonable, but in larger projects, multiple generics of this type may be defined, imported from third-party libraries, leading to a mix of Maybe<T>
, Nullable<T>
, etc. Ensuring consistency across the project can become challenging.
Considering how common this scenario is, I would anticipate a more uniform solution. Is there a better way to handle this?