Search code examples
javascripttypescriptcastingvoidvoid-safety

Is it OK to cast undefined to void in TS?


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?


Solution

  • void is not undefined. void means the absence of a return value. undefined is the type of the value undefined at runtime.

    it is true that a function that returns no value at run time returns undefined, but in the TS type system we chose to make the absence of a return value special.

    For example assigning (a) => void to (a) => number | undefined is likely an error, though it is safe at run-time.

    In general do not use void except in the return type of functions. for everything else, use undefined.

    So, yes we will need to use different check for undefined and void.