如何将可选的命名参数添加到TypeScript函数参数中?(How can I add optional named parameters to a TypeScript function param

编程入门 行业动态 更新时间:2024-10-10 12:23:08
如何将可选的命名参数添加到TypeScript函数参数中?(How can I add optional named parameters to a TypeScript function parameter?)

我希望能够定义一个接受箭头函数作为参数的方法。 函数参数应该能够定义自己的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(()=>{});

更多推荐

本文发布于:2023-08-01 19:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1364491.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   可选   如何将   函数   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!