Reputation: 746
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?
Upvotes: 1
Views: 554
Reputation: 1182
I suppose you are looking for conditional types:
type Caller<T> = (
callback: T extends void ? () => void : (params: T) => void
) => void
Upvotes: 2