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