jainChetan81
jainChetan81

Reputation: 147

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

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 link to error error screenshot

Upvotes: 1

Views: 85

Answers (1)

Konrad
Konrad

Reputation: 24661

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

Upvotes: 1

Related Questions