Working with multiple arguments in typescript

As a newcomer to TypeScript, I am looking to understand how to pass multiple parameters in a TypeScript context. In JavaScript, for example, we would typically do the following:

const createOrUpdate = async (data = {name, email, password}) =>{
    const params = {
        TableName: Table,
        Item: data
    }

    try{
        await db.put(params).promise()
        return { success: true }
    } catch(error){
        return { success: false}
    }
}

I am unsure of how the line data = {name, email, password} can be achieved in TypeScript. Any guidance on this would be greatly appreciated.

Answer №1

TS is essentially JS with added type annotations. Your JS coding style should seamlessly transition to TS. Take a look at this function (excluding async functionality):

const user = "defaultName";
const email = "defaultEmail";
const password = "defaultPassword";


const createOrUpdate = (data = {user, email, password}) =>{
   console.log(data);
}

createOrUpdate();
createOrUpdate({user: "u1", email: "e1", password: "p1"});
  • it accepts a single parameter: data
  • if no parameter is provided, it defaults to an object with 3 fields: user, email, password with values from variables of the same names.

This code is completely valid in TypeScript.

Furthermore, the TS compiler can automatically infer the function's type by analyzing the default argument:

const createOrUpdate: (data?: {
    user: string;
    email: string;
    password: string;
}) => void

You could also explicitly define the parameter's type:

interface UserParams {
    user: string;
    email: string;
    password: string;
}

const createOrUpdate2 = (data:UserParams = {user, email, password}) =>{
   console.log(data);
}

createOrUpdate2();
createOrUpdate2({user: "u1", email: "e1", password: "p1"});

Playground

NOTE: I have replaced name with user. While it is fine for local use, name is a global variable in libdom. See Why does my variable show it is deprecated?

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 practice for Angular: running production build before or after testing?

When developing a Java application for production, I typically set up the build process to create the production artifacts first and then run tests against those artifacts. Recently, I joined an Angular project and noticed that the build process is struct ...

Tips for making a property non-nullable in Typescript

The Node built-in IncomingMessage type from DefinitelyTyped's definition (used as req in the (req, res, next) arguments) has specified that url can be nullable. This excerpt shows part of the definition: // @types/node/index.d.ts declare module "http ...

Error in Typescript index: iterating over properties of a typed object

My scenario involves an interface that extends multiple other interfaces from an external library: interface LabeledProps extends TextProps, ComponentProps { id: string; count: number; ... } In a different section of the codebase, there is an ...

Converting docx files to PDF in Angular 15 using the "docxjs" library: A step-by-step guide

I am currently utilizing the to generate some docx files and enable downloading, but I am faced with the challenge of converting these files into PDF format. This is my current process: public download(data: any): void { const documentCreator = new D ...

Is there a way to start reading a CSV stream from a specific point within the file in S3?

I have a specific query regarding reading CSV data from AWS S3. While I will share information about the technologies involved, they are not central to the main issue at hand. Context (not the core problem, just some additional details) In my scenario, I ...

A guide on connecting multiple select components to a unified Angular 6+ reactive form without triggering redundant updates

I am facing an issue where I need to connect multiple input components to a single angular reactive form, but encounter two main obstacles: By default, only the form in which user input occurs gets updated If I use [(ngModel)] it does work, but it trigge ...

What is the process of attaching a property to every object within an array using TypeScript?

In my search for adding a property to each object in an array, I came across a solution in AngularJs on Stack Overflow. However, I attempted the following approach which did not yield the desired outcome. Any assistance would be greatly appreciated. ex ...

Managing input and output using a collaborative service

I've been working on refactoring some code that contains a significant amount of duplicate methods between two components. Component A is a child of component B, and they can be separate instances as intended. The issue I'm facing revolves around ...

How do you implement a conditional radio button in Angular 2?

I am facing an issue with two radio buttons functionality. When the first radio button is selected and the user clicks a button, the display should be set to false. On the other hand, when the second radio button is chosen and the button is clicked, ' ...

Populating the DOM with a mix of strings and HTMLDivElements by iterating through an array using *ngFor

I have a specific layout requirement that needs to resemble this example: https://i.sstatic.net/4kP2q.png The desired layout should utilize CSS properties like display: grid; someFunction(data) { this.data = data; ...

New feature incorporated at the end of choices in MUI auto-suggest widget

Currently, I'm working on enhancing a category adder feature. Previously, I had limited the display of the "add category chip" to only appear for the no-options render scenario. However, I came across an issue where if there was a category like "softw ...

Tips on resolving issues with cellclickable functionality in Angular with gridster2

VERSION: ^9.3.3 HTML <button (click)="toggleEditing()">{ editing ? 'cancel' : 'editing' }</button> <button>ADD</button> <gridster [options]="options"> &l ...

Instructions for removing all entries from a DynamoDB table

I am facing a challenge with deleting multiple items from a DynamoDB table. While the documentation suggests dropping and recreating the whole table, I want to avoid this approach as my table was created using AWS Amplify and I don't want to risk disr ...

What methods are available to enhance the appearance of a string with TypeScript Angular in Python?

Looking to enhance the appearance of a Python string for display on an HTML page. The string is pulled from a database and lacks formatting, appearing as a single line like so: for count in range(2): global expression; expression = 'happy'; sto ...

Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project I have written a service as shown below: export interface ConfigData { DB_NAME: string; } @Injectable() export class ConfigManager { private static _inst ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

Update the Angular component once new data is saved in a separate Angular component

I've been diving into the world of MEAN stack and Angular, tackling a method within an angular component called itemListDetailsComponent (found in the .ts file) that looks something like this: onStatusUpdateClick() { this.activatedRoute.queryPar ...

Utilizing Typescript to pass props to a material-ui button enclosed in styled-components

After setting up my react project using the typescript template, I decided to style the material-ui Button component using the 'styled' method from the styled-components library as shown below: import React from 'react'; import styled f ...

The back button in the Chrome browser fails to trigger a page refresh within an Angular application

The code snippet above was used in an attempt to refresh the page when the back button is pressed, but it only works inconsistently in Chrome. The issue seems to be that despite correctly detecting the back button press, the page does not always refresh ...

Deriving a universal parameter from a function provided as an argument

My function can take in different adapters along with their optional options. // Query adapter type 1 type O1 = { opt: 1 } const adapter1 = (key: string, options?: O1) => 1 // Query adapter type 2 type O2 = { opt: 2 } const adapter2 = (key: string, opti ...