0

I'm stuck with compile errors while trying to to convert an Object that contains an Array of Objects.

That's what's coming in:

export interface CourseRaw {
  metaInfo: MetaInfoRaw;
  gameCode: number;
  gameText: string;
  images?: ImageRaw[]; // Problems here
}

export interface ImageRaw {
  uploaded: string;
  url?: string;
  description?: string;
  fileName?: string;
}

The output shall be typed objects (interfaces) I have left out many properties here for better reading, hence the "Course" object would look the same as the "CourseRaw" object except for the type "Image[]". Notice that "Image" contains "uploaded" as Date rather than string as seen in "ImageRaw"

export interface Image {
  uploaded: Date;
  url?: string;
  description?: string;
  fileName?: string;
}

In the transforming function I tried to copy the data into a new array, which the compiler doesn't accept:

export class CourseFactory {    
  static fromRaw(courseRaw: CourseRaw): Course {
    return {
      ...courseRaw,      
      ratingInfo: RatingFactory.fromRaw(courseRaw.ratingInfo), // demo of another nested object (works)
      images: ImageFactory.fromRaw(courseRaw.images) // problematic call
    };
  }

My attempt to actually copy the data (failed):

   static fromRaw(imageRaw: ImageRaw[]): Image[] {
    var newImages;

    var i;
    for (i = 0; i < imageRaw.length; i++) {
      newImages[i].uploaded = new Date(imageRaw[i].uploaded);
      newImages[i].url = imageRaw[i].url;
      newImages[i].description = imageRaw[i].description;
      newImages[i].fileName = imageRaw[i].fileName;
    }
    return newImages;
  }

How can I make it right?

1 Answers1

0

You should type the Image return array. Furthermore you can add a map to to do it easily.

static fromRaw(imageRaws: ImageRaw[]): Image[] {
  return imageRaws.map(raw => {
    return {
      uploaded: new Date(...),
      url: raw.url,
      // etc.
    }
  });
}

Since array creation is in the return instruction, TS should get the typings right.

About your code:

  1. You can make it work adding var newImages: Image[] = []; (initialization and type definition)
  2. You should use push to add new items to the array; if you really want to initialize array length (see related question/answer ), you should add newImages.length = imageRaws.length.
leonardfactory
  • 3,353
  • 1
  • 18
  • 25