简体   繁体   中英

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 :

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. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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