在Typescript中将Object作为函数参数传递

jq6vz3qz  于 2022-11-30  发布在  TypeScript
关注(0)|答案(2)|浏览(199)

我正在开发一个包含函数的Angular组件。在这个函数中,我需要传递一个Object作为函数参数,并用函数参数调用这个函数。我已经有一段时间没有使用Angular了,在类型上,“any”是函数的返回类型;现在它似乎是“未定义的”。2但是,我不知道如何写函数调用与相应的参数,并希望任何帮助和提示。3提前感谢!
下面是组件:

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

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

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

  constructor() {
    // Called first time before the 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);

  }
}

下面是需要在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);

  }

这是ngOnInit中的函数调用,在这里我在正确传递参数时遇到了麻烦:

public ngOnInit(): void {

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

  }

this.userdata不能作为函数参数传递;编译器错误为:

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

我尝试使用相应的参数调用ngOnInit方法中的函数。得到的错误是:类型为“Object”的参数不能赋值给类型为"{ FirstName: unknown; LastName: unknown; }"的参数。我不能告诉如何正确地将对象作为函数参数传递。

yqkkidmi

yqkkidmi1#

可以导出为单独的接口:

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

然后道:

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

xhv8bpkk2#

首先,您需要为userData创建一个类型:

type UserData = { FirstName: string; LastName: string };

然后,您应该使用UserData类型来输入userData属性和参数。
属性:

@Input() public userdata!: UserData;

参数:

public NewWorkItem(interactionID: unknown, userData: UserData): void  {

相关问题