Using an Object as a parameter in a Typescript function

I am currently working on an Angular component that includes a function. Within this function, I need to pass an Object as a parameter and invoke the function with these parameters. It has been some time since I last worked with Angular, where "any" was typically used as the return type for functions. Nowadays, it appears that "undefined" is more common. However, I am unsure of how to correctly write the function call with the appropriate parameters. Any assistance or tips would be greatly appreciated. Thank you in advance!

Below is the code snippet for the component:

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {

  public interactionID: number = 0;
  @Input()
  public userdata!: Object;


  constructor() {
    // Constructor called before ngOnInit()
  }

  public ngOnInit(): void {
    this.NewWorkItem(this.interactionID, this.userdata);
  }

  public NewWorkItem(interactionID: unknown, userData: { FirstName: unknown; LastName: unknown }): void {
    console.log('NewWorkItem call', interactionID, userData);

    const event: Event = new CustomEvent ('wde.newWorkItem', {
      detail: {
        FirstName: userData.FirstName,
        LastName: userData.LastName,
        InteractionID: interactionID
      },
      bubbles: true,
      cancelable: true,
      composed: false,
    });
    console.log('NewWorkItem event', event);
    window.dispatchEvent(event);

  }
}

This is the function that should be called within ngOnInit:

public NewWorkItem(interactionID: unknown, userData: { FirstName: unknown; LastName: unknown }): void  {
    console.log('NewWorkItem call',interactionID,userData);

    const event: Event = new CustomEvent ('wde.newWorkItem', {
      detail: {
        FirstName: userData.FirstName,
        LastName: userData.LastName,
        InteractionID: interactionID
      },
      bubbles: true,
      cancelable: true,
      composed: false,
    });
    console.log('NewWorkItem event',event);  
    window.dispatchEvent(event);

  }

Here is where I am facing issues while passing the parameters correctly in ngOnInit:

public ngOnInit(): void {

  this.NewWorkItem(this.interactionID, this.userdata );

}

The compiler error I encounter is due to issues with passing the userdata object as a function parameter:

The argument of Typ "Object" cannot be assigned to the parameter of type "{ FirstName: unknown; LastName: unknown; }"

In my attempt to call the function within ngOnInit with the correct parameters, I encountered the following error message: The argument of Typ "Object" cannot be assigned to the parameter of type

"{ FirstName: unknown; LastName: unknown; }"
. I am unsure about the proper way to pass the object as a function parameter.

Answer №1

When exporting, consider using a separate interface:

export interface IUserData { FirstName: unknown; LastName: unknown }

After defining the interface, utilize it in your code like this:

@Input() public userdata!: IUserData;
...
public NewWorkItem(interactionID: unknown, userData: IUserData);

Answer №2

To start off, the initial step involves defining a structured type for user information:

type UserInformation = { firstName: string; lastName: string };

Subsequently, make use of the UserInformation type to assign types to the userData property and parameter.

userData property:

@Input() public userInfo!: UserInformation;

userData parameter:

public createNewUser(interactionCode: unknown, userInfo: UserInformation): void {

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

Using Bazel, Angular, and SocketIO Version 3 seems to be triggering an error: Uncaught TypeError - XMLHttpRequest is not recognized

Looking to integrate socket.io-client (v3) into my Angular project using Bazel for building and running. Encountering an error in the browser console with the ts_devserver: ERROR Error: Uncaught (in promise): TypeError: XMLHttpRequest is not a constructor ...

Is it necessary to install ng-bootstrap if my project was built using the Bootstrap 4 alpha theme in Angular 4?

I am currently utilizing the SB-Admin-BS4-Angular-4-master theme in Angular 4. The theme includes a link to . My goal is to implement Bootstrap modals in my code. Following the documentation provided in the theme, I integrated the modals as per instruction ...

Issue: The system needs the 'image' property to proceed (Dall E's image variation API by OpenAI)

Utilizing the Dall E Create image variation API has been a bit challenging for me. Every time I send a post request, I encounter this particular error: error: { "code": null, "message": "'image' is a required property&q ...

What is a way to incorporate two ngClass directives within a single div element?

Is it possible to include two ng-class directives within a single div element? If so, how should we go about writing them together? Thank you for your help. <div [ngClass]={'white-background': policyNumber.length <= 0} [ngClass]="getS ...

TypeScript class featuring a unique method that is not utilized in every instance

I have a TypeScript class that is managing ZMQ bus communication. Initially, I created a general class that can be instantiated multiple times. However, now I need to create instances with slight variations that do not perfectly fit the generic class I o ...

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...

When implementing 'useGlobalGuards' in NestJS, remember to exclude endpoints for enhanced security

After implementing the useGlobalGuards method in my main.ts file, all endpoints now utilize the AuthGuard. This guard triggers a 401 error if a valid auth token is not present in the request header. Previously, I used @UseGuards(AuthGuard) on individual cl ...

The expiration of the Gitlab CI/CD cache leads to the failure of the build process

I have an AWS CDK application in TypeScript and a simple GitLab CI/CD pipeline with 2 stages for deployment: image: node:latest stages: - dependencies - deploy dependencies: stage: dependencies only: refs: - master changes: - ...

Debugger for Visual Code unable to locate URL in Microsoft Office Add-in

I recently installed the Microsoft Office Add-in Debugger VS code extension, but I'm having trouble getting it to work despite following the instructions. Every time I try, an error message pops up: Upon inspecting my launch.json file, I found this U ...

How come TypeScript tuples support the array.push method?

In the TypeScript code snippet below, I have specified the role to be of Tuple type, meaning only 2 values of a specified type should be allowed in the role array. Despite this, I am still able to push a new item into the array. Why is the TS compiler not ...

Utilizing Angular 2: Implementing a template-driven form to send data from a chosen element to the submitting object

Hey there! I'm fairly new to Angular 2 and have been trying to tackle this issue for a while now. I have a user object that contains another nested object, defined by the User interface: export interface UserModel{ name: string, service: Service ...

How to transfer files between Dropbox and AWS S3 using Angular 5

Currently, I'm utilizing the Dropbox file picker to download a file. Once a file is selected using the Dropbox picker, I obtain the download link. I'm wondering if it's possible to save it as a bytestream in the browser and then upload it t ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

Ways to dynamically update a Vuetify 3 element's placeholder text?

Here is the code snippet from my component.vue file: <template> <v-text-field name="Foo" :label="$t('foo')" type="text" hint="This is a hint" persistent-hint >& ...

Initial position of the range slider in IONIC 2

I have been searching the web extensively to find a solution to this particular issue. I am working with a range slider and trying to set its default starting values, but so far, I haven't had any luck. I've checked both the official documentatio ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Guide for building a Template-driven formArray in Angular

I am currently implementing a fixed number of checkboxes that are being bound using a for loop. <ul> <li *ngFor="let chk of checkboxes"> <input type="checkbox" [id]="chk.id" [value]="chk.value&q ...

retrieve the key associated with a translated value using ngx-translate

Using @ngx-translate along with localize-router has posed a challenge for me. I am unable to resolve a valid slug from a localized URL. For example, if the translation of 'about' is 'asd', then: routerLink="about/{{'about' ...

What is causing the error to appear in my Jasmine unit test?

Embarking on my journey to implement an Angular Unit Test using Jasmine for the first time, I encountered a few challenges after referring to some examples. The crux of my issue lies in the implementation of the PeopleListComponent class which encapsulate ...

How to set the default theme color for the mat-sidenav background in Angular 6 and 7?

Is there a way to make the background of a mat-sidenav match the theme color of my mat-toolbar? In the file src\styles.scss, I have the following: @import '~@angular/material/prebuilt-themes/indigo-pink.css'; The template / HTML file incl ...