【问题标题】:Assign starting null values and initialize array of objects in TypeScript在 TypeScript 中分配起始空值并初始化对象数组
【发布时间】:2021-07-20 09:37:40
【问题描述】:

这是我的模型:

export interface IUser{
    id: number;
    firstName: string;
    lastName: string;
    accounts?:
    {
        userID: number;
        accType: AccType;
        badges: Badge[];
        accountStatus: AccStatus;
    }[];
}

在我的 user.service.ts 中,我在将用户用于 HTTP 服务之前对其进行初始化。但似乎无法正确初始化帐户,因为我无法访问其值。

private initializeUser(): IUser{
    return {
      id:0,
      firstName: null as any,
      lastName: null as any,
      accounts:{
         userID: null as any,
        accType: null as any,
        badges: null as any,
        accountStatus: null as any
        }
    };
  }

另外,我认为由于徽章是一个数组,所以我也错误地初始化了它们。

【问题讨论】:

    标签: angular typescript interface


    【解决方案1】:

    我建议让 ids 兼任。它将让您知道用户是否是新用户。

    export interface IUser {
        id?: number;
        firstName: string;
        lastName: string;
        accounts?:
        {
            userID?: number;
            accType: AccType | null;
            badges: Badge[];
            accountStatus: AccStatus | null;
        }[];
    }
    
    
    private initializeUser(): IUser{
        return {
          firstName: '',
          lastName: '',
          accounts:[{        // Don't forget the [...], it's an array
            accType: null,
            badges: [],
            accountStatus: null
          }]
        };
      }
    

    【讨论】:

      【解决方案2】:
      private initializeUser(): IUser{
          return {
            id:0,
            firstName: null as string,
            lastName: null as string,
            accounts:{
               userID: null as number,
              accType: null as accType,
              badges: null as Badge[],
              accountStatus: null as AccStatus
              }
          };
        }
      

      【讨论】:

        猜你喜欢
        • 2018-06-26
        • 2022-08-12
        • 2013-09-02
        • 2012-11-17
        • 1970-01-01
        • 2020-09-04
        • 2019-03-08
        • 2020-05-04
        • 2016-09-01
        相关资源
        最近更新 更多