Is there an easier method to utilize ES6's property shorthand when passing an object in TypeScript, without needing to prefix arguments with interface names?

When working with JavaScript, I often find myself writing functions like the one below to utilize ES6's property shorthand feature:

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

//Usage:
const param1 = "param1";
const param2 = "param2";
exampleFunction({param1, param2});

Now, when attempting to write this function in TypeScript, I encounter a slight inconvenience:

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

Although it works fine, I find myself having to prefix the arguments with "arg" and provide a redundant name ("arg") every time I define the function. Is there a way in TypeScript to avoid this by directly using the argument names without specifying the interface each time? I envision something like this:

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

A cleaner and simpler approach that still offers the advantages of TypeScript. Is there a solution to achieve this?

Answer №1

Sorry, but what you are attempting to achieve is not feasible. According to the guidelines:

When it comes to destructuring parameter declarations, type annotations are not allowed on the individual binding patterns. This restriction is in place to prevent conflicts with the existing use of colons in object literals. Type annotations must instead be included in the top-level parameter declaration.

One way to implement destructuring (with or without shorthand syntax) is as follows:

interface MyParameterObj { param1: string, param2: string }

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

Alternatively, you can define the interface inline:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

Should we enable client-side validation and unobtrusive JavaScript in the Web.config file?

I'm currently working on an ASP MVC application, where all form and UI code is written in AngularJS for validation purposes. I didn't use any HTML helpers. Do I need to include the entries ClientValidationEnabled and UnobtrusiveJavaScriptEnabled ...

Having trouble with triggering a Material UI modal from a Material UI AppBar on a Next.js page

As a newcomer to the world of React.js and Next.js, I am encountering difficulties when trying to open a Material UI modal from a Material UI AppBar within a Next.js page. Most of the code I have implemented here is directly copied from the Material UI we ...

What is the best way to ensure PyScript is completely initialized, including the environment?

Hey there! I'm hoping to catch a specific message being logged in my browser's console by a script I added to my HTML file, and then trigger a JavaScript action based on that. For instance, when "ABCD:READY" appears in the console, I want to cal ...

Adjust the border color of Material UI's DatePicker

https://i.sstatic.net/ZvNOA.png Hello everyone, I am currently working with a DatePicker component from Material UI. My main goal is to change the border color of this component. I have attempted various methods such as modifying classes, adjusting the th ...

Setting Authorization with username, password, and domain in Angular 2 HTTP Request

I am facing an issue with calling an API method hosted on another machine using Angular 2 component with Http. When accessing the API from a browser, I can connect by entering a username and password as shown below: https://i.stack.imgur.com/JJqpC.png Ho ...

Encountering a NaN outcome when summing values from various select options

I'm working on a project that involves adding up the prices based on the surface chosen by the user. I'm struggling with calculating the partial cost when the user's choice changes. totalSum.ts num: Calculation totalAmount: number cate ...

The issue of slides overlapping in a Javascript slideshow during auto play mode

I encountered an issue while creating an automatic slideshow with 4 slides. Upon autoplay for the first time, slide 1 overlaps slide 4, as well as slide 2 and 3. This only happens once after the site loads. However, on subsequent playthroughs or when using ...

Tips on transitioning between two tables

Recently, I created an HTML page entirely in French. Now, I am attempting to incorporate a language translation feature on the website that allows users to switch between French and English (represented by two flag icons). My concept involves using a tabl ...

Why does the image return an Undefined Value when clicked? Is there a solution to this issue?

Every time I click on an image, I encounter the error message "undefined." Can someone please shed some light on why this is happening and provide guidance on how to successfully retrieve and pass the value to the onclick function in this particular scen ...

Utilize TypeScript to define the types based on the return values produced by an array of factory functions

My application features multiple factory functions, each returning an object with specific methods (more details provided below). I am interested in creating a type that combines the properties of all these returned objects. const factoryA = () => ({ ...

Creating QR codes from raw byte data in TypeScript and Angular

I have developed a basic web application that fetches codes from an endpoint and generates a key, which is then used to create a QR Code. The key is in the form of an Uint8Array that needs to be converted into a QR Code. I am utilizing the angularx-qrcode ...

I am having trouble with the Array Reverse function, it's not functioning properly

Take a look at this React JS code snippet: poll() { var self = this; var url = "//" + location.hostname + "/api/v1/eve/history/historical-data/" + this.state.itemId + '/' + this.state.regionId + '/40'; $.get(url, fu ...

Learn how to dynamically disable a button based on the input state matching an email pattern!

I'm facing an issue with my login form that has 2 input fields and a login button. One of the input fields requires a valid email pattern. If any of the input fields are left empty, the login button becomes disabled. However, when an incorrect email p ...

Vue.js is updating state, yet the view remains static and does not re-render

My experience with learning Vue.js has been great, but I keep encountering a problem where setting a data property based on state doesn't update the component when the state changes. For instance... Check out these code snippets <router-link v-i ...

I'm having trouble with my TextGeometry not displaying on screen. Can someone help me figure

Here is the code I am using for Three.js: <html> <head> <title>My first Three.js app</title> <style> body { margin: 0; } canvas { width: 100%; height: 100% } </style> ...

Typegoose and NestJS: The 'save' property is not found on this type

I recently started using typegoose and nestjs for my backend-server. In my pages.service.ts file, I already have a function called getPageById() to retrieve a single page by its ID. However, when trying to call this function from another function within th ...

Ensure your HTML5 videos open in fullscreen mode automatically

I managed to trigger a video to play in fullscreen mode when certain events occur, such as a click or keypress, by using the HTML 5 video tag and jQuery. However, I am now looking for a way to have the video automatically open in fullscreen mode when the p ...

What is the best way to handle a ReadableStream for a POST request?

I'm currently working on implementing basic CRUD operations using the latest Next.js 13 route handlers in combination with Prisma using TypeScript. This is how my POST request handler appears: export async function POST(req: NextRequest) { const c ...

Ways to validate a foreign key in Strongloop?

I am faced with a situation where I have a collection of categories and a separate collection of places, with each place having a foreign key that corresponds to a category ID. You can find the list of categories in categorie.json: http://pastebin.com/ttu ...