Home > OS >  How to use Typescript generics when the argument could be a value or callback function
How to use Typescript generics when the argument could be a value or callback function

Time:02-01

So here the problem is that I want to pass T which could be string, number, boolean, object or array or a function the thing is I can't figure out how to process ab("hello") in this case and have T returned back as a value.

function a<T>(ab: T | ((v: T) => T)) {
    if (typeof ab === "function") {
        return ab("hello");
    } else return ab;
}

this is the error I have been seeing and error screenshot

CodePudding user response:

You have to restrict your T to not be a function

function a<T>(ab: T extends Function ? never : T | ((v: T) => T)) {
    if (typeof ab === "function") {
        return ab("hello");
    } else return ab;
}

playground

Based on this answer https://stackoverflow.com/a/63045455/5089567

Maybe there is another solution, but I don't know it

  • Related