簡體   English   中英

將對象推送到嵌套的 Typescript 數組中,得到錯誤:無法讀取未定義的屬性“推送”

[英]Push object into nested Typescript array, get error: Cannot read property 'push' of undefined

我一直在四處尋找試圖解決這個問題,但我的代碼似乎有點超出標准的“將對象推入數組”。

我有一個接口,它使用另一個接口作為數組鍵入“Year”屬性:

   export interface IUser {
        Nickname: string;
        FirstName: string;
        LastName: string;
        Email: string;
        EmergencyContact: string;
        EmergencyNumber: string;
        Year: Array<IYear>;
        IsTeacher: boolean;
        IsAdmin: boolean;
        Uid: string;
    }

    export interface IYear {
        CalendarYear: string;
        PassType: string;
        UserItinerary: IItinerary;
        WaiverStatus: boolean;
        Guests: Array<IGuest>;
        SignupDate: string;
    }

在某個時候,我將一些 formGroup 數據傳遞到 IYear 類型屬性中:

user: IUser = <IUser>{};

createUser(
    firstName: string,
    lastName: string,
    email: string,
    uid: string,
    isTeacher: boolean,
    passType: string) {
    const year: IYear = {
      CalendarYear: this.calendarYear,
      PassType: passType,
      UserItinerary: {} as IItinerary,
      WaiverStatus: false,
      Guests: [],
      SignupDate: this.dateTime
    }
    this.user.FirstName = firstName;
    this.user.LastName = lastName;
    this.user.Email = email;
    this.user.Uid = uid;
    this.user.IsTeacher = isTeacher;
    this.user.IsAdmin = false;
    this.user.Year.push(year);

    return this.user;
  }

問題是,當我嘗試將 createUser 中的 'year' 屬性傳遞到 'this.user.Year' 數組時,出現錯誤

無法讀取未定義的屬性“推送”

我已經嘗試通過鍵顯式傳遞值:

this.user.Year['CalendarYear'] = year.CalendarYear;

但這沒有用。 有人能在這里指出我的錯誤嗎?

在將對象推入其中之前,用戶對象中的 Year 數組應初始化為空。

this.user.Year = [];

進而,

this.user.Year.push(year);

出現錯誤的原因是您必須首先初始化一個 array ,然后才能向其push()值。

  • 要么用year = [{your year}]初始化一個新的IUser然后你可以向它推送更多的值。
  • 或者用一個空數組 year 初始化一個新的IUser對象,然后你可以向它推送值。

您已在使用之前初始化您的數組。

user: IUser = <IUser>{};    
createUser(
    firstName: string,
    lastName: string,
    email: string,
    uid: string,
    isTeacher: boolean,
    passType: string) {
    const year: IYear = {
      CalendarYear: this.calendarYear,
      PassType: passType,
      UserItinerary: {} as IItinerary,
      WaiverStatus: false,
      Guests: [],
      SignupDate: this.dateTime
    }
    this.user.FirstName = firstName;
    this.user.LastName = lastName;
    this.user.Email = email;
    this.user.Uid = uid;
    this.user.IsTeacher = isTeacher;
    this.user.IsAdmin = false;
    this.user.Year=[];
    this.user.Year.push(year);    
    return this.user;
  }

您需要確保Year存在於用戶對象上,並且CalendarYear存在於Year對象上

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM