简体   繁体   中英

How can I add optional named parameters to a TypeScript function parameter?

I'd like to be able to define a method that accepts an arrow function as a parameter. The function parameter should be able to define 0 or more named parameters of its own. How can I do this?

I've tried

public doSomething(fn: () => any) {}

and

public doSomething(fn: (...args) => any) {}

but they both throw a "supplied parameters do not match" error when I try to call it as follows:

doSomething((test: string) => {})

( Note that the type and number of parameters to this function may vary on each usage, so I can't set the type(s) on the original method. )

I can supply parameters using the ...args syntax within the passed function, but I would like to be able to type and name specific parameters.

Is there a way to do this?

Two options. Reasons Type Safety . If you work through the statements below it should be clear.

Fix the callback:

If your function expects to call the callback with 0 or more arguments, then the callback must be okay with it (ie have optional arguments) ie

function doSomething(fn: () => any) {}

// All arguments need to optional 
doSomething((a?:string)=>{});

Same as :

function doSomething(fn: (...args:string[]) => any) {}

// All arguments need to optional 
doSomething((a?:string)=>{});

Fix the callback signature:

If you are going to call the callback with exactly 'N' arguments, specify their names in the signature. It is up to the callback to take or ignore these. Eg. this callback ignores them:

// Specify the number of arguments
function doSomething(fn: (ar1:string,arg2:string) => any) {}

doSomething(()=>{});

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