Home > Software engineering >  Can't call a function even with typeof type guard
Can't call a function even with typeof type guard

Time:07-03

function func<T>(param: T | (() => T)) {
    // @ts-expect-error
    return typeof param === "function" ? param() : param;
}

Even with the typeof type guard, I can't invoke param and this is only when I have a generic function, it works otherwise:

function func(param: string | (() => string)) {
    return typeof param === "function" ? param() : param;
}

I've no clue as to why this is happening and what's the fix, I would really appreciate some help!

CodePudding user response:

You can declare a type guard that checks if the param is a function or not.

function isFunction (arg: unknown): arg is Function {
  return typeof arg === "function"
}

and then you can use it like this

function func<T>(param: T | (() => T)) {
    return isFunction(param) ? param() : param;
}

You can see this in action in this playground

  • Related