简体   繁体   English

使用ES6的属性速记来传递带有Typescript的对象并避免在接口名称前加上参数的简化方法?

[英]Simplified way to use ES6's property shorthand to pass an object with typescript and avoid prefacing arguments with interface name?

In javascript, I write a lot of functions like the following to take advantage of ES6's property shorthand : 在javascript中,我编写了许多类似以下的函数,以利用ES6的属性速记

function someFunction({param1, param2}) {
  console.log(param1 + " " + param1);
}

//I call it like this:
const param1 = "param1";
const param2 = "param2";
someFunction({param1, param2});

Here is how I'm writing this function in typescript: 这是我在打字稿中编写此函数的方式:

function someFunction(arg: {param1: string, param2: string}) : string {
  return arg.param1 + " " + arg.param2;
}

This works fine, but now I need to preface my arguments with "arg" every time in the function body and I need to give the argument a useless ("arg") name every time. 这很好用,但是现在我每次在函数体中都需要在参数前面加上“ arg”,并且每次都需要给参数一个无用的(“ arg”)名称。 Is there a way to do this in typescript where I can call these arguments directly without prefacing their interface name? 有没有一种方法可以在打字稿中做到这一点,在这里我可以直接调用这些参数而无需添加其接口名称? And avoid naming an interface every time? 并避免每次都命名接口? Ideally I'd like to be able to do this: 理想情况下,我希望能够做到这一点:

function someFunction({param1: string, param2: string}) : string {
  return param1 + " " + param2;
}

Much cleaner and more simple to write and still gives me all the benefits I want from typescript. 更简洁,更容易编写,仍然为我提供了打字稿所需的所有好处。 Is there any way to achieve this? 有什么办法可以做到这一点?

No, what you are trying to do is not possible. 不,您试图做的事是不可能的。 From the specification : 规格

Destructuring parameter declarations do not permit type annotations on the individual binding patterns, as such annotations would conflict with the already established meaning of colons in object literals. 解构参数声明不允许在单个绑定模式上进行类型注释,因为此类注释将与对象文字中冒号的已确定含义冲突。 Type annotations must instead be written on the top-level parameter declaration. 必须将类型注释写在顶级参数声明上。

You can use destructuring (with or without shorthand syntax) as following: 您可以按如下方式使用解构(具有或不具有简写语法):

interface MyParameterObj { param1: string, param2: string }

function someFunction({param1, param2}: MyParameterObj) : string {
  return param1 + " " + param2;
}

but also inline the interface: 而且内联接口:

function someFunction({param1, param2}: {param1: string, param2: string}) : string {
  return param1 + " " + param2;
}

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

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