TLDR;
Is this OK? Or is it bad practice?
function isUndefined (payload: any): payload is undefined | void {
return payload === undefined
}
Context
In TypeScript, I have a function that can return either something or undefined
or void
.
Something like an event handler that can return a modified payload or the dev can choose to return nothing or undefined in case they won't modify the payload:
function eventHandler <T extends {[key: string]: any}> (payload: T): Modified<T> | undefined | void {
// ... implementation
}
Then I have a type checker that needs to check if it's returning something other than void or undefined:
const result = eventHandler(payload)
if (result !== undefined) {
// we have a modified payload!
}
However, is the above snippet I get an error because it says that even though result !== undefined
it can still be void
?
In my opinion, I think it's peculiar because void
should be the same as undefined
.
So I made this type checker that solves it:
function isUndefined (payload: any): payload is undefined | void {
return payload === undefined
}
This solves my issue, but my question is:
Is this OK? Or is it bad practice?