Can a single data type be utilized in a function that has multiple parameters?

Suppose I have the following functions:

add(x : number, y : number)
subtract(x : number, y : number)

Is there a way to simplify it like this?

type common = x : number, y : number

add<common>()

This would prevent me from having to repeatedly define the same parameters.

Answer №1

Carlo's response is in the right direction, but I would approach it using spread arguments and a named tuple:

type X_Y = [x: number, y: number];

function sum(...args: X_Y) { return args[0] + args[1] };
function difference(...args: X_Y) { return args[0] - args[1] };

sum(1, 2);
difference(1, 2);

If the output type is always consistent, you might want to consider defining one type for the entire process:

type Operation = (x: number, y: number) => number;

const add: Operation = (x, y) => x + y
const substract: Operation = (x, y) => x - y

add(1, 2)
subtract(1, 2)

Answer №2

Perhaps not the most graceful solution, but here is a quick and dirty way to achieve the desired result:

type x_y = [number,number];
function add(i:x_y){
  return i[0]+i[1];
}

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

Is it possible to target an element using the data-testid attribute with #?

Is there a shortcut for selecting elements with the data-testid attribute in playwright-typescript? await page.locator("[data-testid='YourTestId']").click() I attempted to use await page.locator("[data-testid='YourData-testid ...

How can I import a node-js dependency into my webpack project when the package already comes with type definitions included?

Don't bother using the deprecated @types/chalk package because the chalk library already has type definitions included. But I keep encountering the error message TS2307: Cannot find module 'chalk'. https://i.sstatic.net/uDIJi.png The proje ...

Introducing NextAuth: Empowering multiple users to access a single account

I've been pondering if it's possible to have multiple users for a single account provider. One idea is to create a session with a specific field indicating the active user (the one currently logged in) and then allow for easy switching between us ...

Angular 6 is throwing an error message stating that it cannot access the 'image' property of an undefined object

Having trouble retrieving the details, as it is rendering to the dom with an undefined error. Check out this image for reference: Welcome to the Book Details Component export class BookDetailsComponent implements OnInit { book: Book; books: Book[]; ...

Session is not functioning properly as anticipated

import * as express from 'express'; import * as session from 'express-session'; import * as bodyParser from 'body-parser'; const app: express.Express = express(); app.use(bodyParser.json()); app.use(session({ secret: &apos ...

When attempting to send an archiver file in NodeJS, the request may become unresponsive

In my NextJS application, I am facing the challenge of generating a large number of QR codes at once, like 300, 400, or even 500, and then packaging them into a zip file for users to download. The following code snippet demonstrates how I achieve this usin ...

Dealing with numerous errors from various asynchronous pipes in angular - a comprehensive guide

I am facing an issue with 2 mat-select elements in my component, both of which utilize the async pipe: <div class="flex-col"> <mat-label>Issue Desc </mat-label> <mat-form-field> < ...

Icon for TypeScript absent from npm package listings

Recently, I created a package and uploaded it to the npm repository. The package was displayed with an icon labeled "ts" on the website. https://i.stack.imgur.com/LoY1x.png The accompanying package.json showcased the inclusion of the "ts" icon - https:// ...

The Ion-item-option button requires two clicks to activate

Within my ion-list, I have sliding items that are dynamically created using a for loop. Interestingly, when clicking on an item to navigate to another page, everything works fine. However, upon sliding an item, a button is revealed but it requires two clic ...

Ways to incorporate debounce time into an input search field in typescript

Is there a way to incorporate debounce time into a dynamic search box that filters data in a table? I have explored some solutions online, but my code varies slightly as I do not use throttle or similar functions. This is my template code: <input matI ...

How can I display every index from my JSON Fetched Files?

In the picture shown here, I have a series of Tables being displayed: The issue highlighted in red is that I want to show the Index of each JSON array as the Table number. Below is the code snippet: function getExternal() { fetch('https://kyoala ...

Discovering all images in Angular

I have a function that stores image data, including the name. Using *ngFor, I am able to fetch this data from the database and display it in boxes. HTML <div class="row tab-pane Galeria"> <div *ngFor="let product of products" (click)="Im ...

Apologies, but it seems there was an issue with the installation of the "@angular/compiler-cli" package

Despite thoroughly searching through various threads, I am still unable to find a solution to my problem. I have cloned the angular2 quickstart project and ensured that all module versions are up to date. For reference, here is the link to the repository ...

Can a file be transferred from the private path to the document directory?

I wrote this code using the captureVideo() method from the Ionic Native MediaCapture plugin. Here is the file path I obtained: /private/var/mobile/Containers/Data/Application/95DB5A64-700B-4E3D-9C2C-562C46520BEC/tmp/52515367181__BBC39D42-69EC-4384-A36F-7 ...

Is there a way to ensure that a certain block of code in Typescript is executed only after an API call has been completed?

When making an API call, I need the code after the call to wait until the API call finishes. In my function called this.api_call, it calls the API and only returns an array returnValue once the call is complete. let returnValue = this.api_call(data); // ...

Modify the property of the ChildComponent by utilizing the ViewChild method

I recently started exploring Angular and I've been experimenting with ViewChild and ViewChildren. In one scenario, I have a property called today = new Date() in my Component2. I'm accessing this property in Component1 using ViewChild and continu ...

Retrieving an array of objects from an API and attempting to store it using useState, but only receiving an empty

I have been working on fetching data from an API, storing it in Redux store initially, and then attempting to retrieve it using useSlector to finally save it in local state. Despite getting the data when I console.log it, I am unable to successfully store ...

Is there a way to add zeros at the beginning of ZIP codes that have only 3 or 4 digits using LODASH or Typescript?

Looking at the JSON data below, it includes information on USPS cities, states, counties, latitude, longitude, and zip codes. With over 349,000 lines of data, it's very extensive. ... { "zip_code": 988, "latitude": 18.39 ...

The Angular route successfully navigated to the page, but the HTML content was not

Whenever I select the Home option in the navigation bar, it takes me to the home URL but doesn't display the HTML content. Below is my app.routing.module.ts code: import { Component, NgModule } from '@angular/core'; import { RouterModule, Ro ...

Module 'ngx-bootstrap' not found in project

My application is encountering an issue with ngx-bootstrap where the module can no longer be detected unless the path is specified. For instance: import { BsModalService, BsModalRef } from 'ngx-bootstrap'; results in "Cannot find module ' ...