简体   繁体   English

带部分类型注释的TypeScript函数参数解构

[英]TypeScript function argument destructuring with partial types annotation

Let's consider example: 让我们考虑示例:

function func1(num: number) {
  return num * 2;
}

function func2(by: number, num = func1(1)) {
  return num / by;
}

It works perfectly fine. 它工作得很好。 In func2 I don't have to manually provide a type for num argument since it is provided from func1 . func2我不必手动为num参数提供类型,因为它是由func1提供的。

But when I write func2 in form of argument object destructuring I have to manually provide a type for num in func3 : 但是,当我以参数对象func2的形式编写func2 ,我必须在func3手动提供num的类型:

function func3({ by, num = func1(1) }: { by: number, num: number }) {
  return num / by;
}

How to write func3 without retyping type for num ? 如何编写func3而不重新键入num类型? Something like this (code below doesn't work): 这样的事情(下面的代码不起作用):

function func3({ by, num = func1(1) }: { by: number }) {
  return num / by;
}

There is currently no better way to do this unfortunately. 不幸的是,目前没有更好的方法。 Ideas about improving this have been floating around for a while but the compiler team has not found a good one yet. 改善这一想法的想法已经浮出水面了一段时间,但是编译器团队尚未找到一个好的想法。 This issue is the latest proposal, @RyanCavanaugh says they are giving it another try, well see what comes of it. 这个问题是最新的建议,@ RyanCavanaugh说,他们正在再次尝试,请看看结果如何。 For now you have to write the names again in the type annotation 现在,您必须在类型注释中再次写入名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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