简体   繁体   中英

TypeScript: Type with callback with generically optional parameter

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?

I suppose you are looking for conditional types :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM