我希望能够定义一个接受箭头函数作为参数的方法。 函数参数应该能够定义自己的0个或多个命名参数。 我怎样才能做到这一点?
我试过了
public doSomething(fn: () => any) {}和
public doSomething(fn: (...args) => any) {}但是当我尝试按如下方式调用它时,它们都抛出“提供的参数不匹配”错误:
doSomething((test: string) => {})( 请注意,此函数的参数类型和数量可能因每次使用而异,因此我无法在原始方法上设置类型。 )
我可以在传递的函数中使用...args语法提供参数,但我希望能够键入和命名特定的参数。
有没有办法做到这一点?
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?
最满意答案
两种选择。 原因类型安全 。 如果您完成以下陈述,则应该清楚。
修复回调:
如果你的函数期望用0或更多的参数调用回调,那么回调必须是可以的(即有可选的参数),即
function doSomething(fn: () => any) {} // All arguments need to optional doSomething((a?:string)=>{});与...一样 :
function doSomething(fn: (...args:string[]) => any) {} // All arguments need to optional doSomething((a?:string)=>{});修复回调签名:
如果要使用'N'个参数调用回调,请在签名中指定它们的名称。 取决于采取或忽略这些回调。 例如。 这个回调忽略了它们:
// Specify the number of arguments function doSomething(fn: (ar1:string,arg2:string) => any) {} doSomething(()=>{});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 (i.e. have optional arguments) i.e.
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(()=>{});更多推荐
发布评论