1

I have found many similar questions here but I couldn't find my particular problem. I want to have a generic type which defines the type of the parameter that its callback takes, and "no parameter" should be an option.

What I don't want: the callback parameter to be optional in the sense that when the callback is called, the parameter can be passed or not

What I want: When I specify the generic parameter, I want to be able to say that the callback must take no arguments.

type Caller<T> = (
    callback: (params:T)=>void
) => void

// none of this works:

let caller1:Caller<void> = function(
    callback: ()=>void
){}

let caller2:Caller<never> = function(
    callback: ()=>void
){}

let caller3:Caller<undefined> = function(
    callback: ()=>void
){}

// this works-ish but is ugly:

let caller4:Caller<void> = function(
    callback: (_:void)=>void
){}

I have also read this https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html but I think that my problem is one level higher than this.

How can I do this?

1 Answer 1

2

I suppose you are looking for conditional types:

type Caller<T> = (
    callback: T extends void ? () => void : (params: T) => void
) => void
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.