Home > Software design >  setting type of index in for of loop in Typescript
setting type of index in for of loop in Typescript

Time:11-07

I am trying to set the type of an item when I loop through a response which is an array of objects, however, I am not sure how to declare the type.

I have the following type:

export type Movie = {
  title: string;
  director: string;
  year: string;
};

I get the following response from an api

const movies = [{
    "movie": {
        "title": 'The Dark Knight',
        "director": 'Christofer Nolan',
    },
    
    "details": {
        "year": 2008,
        "rating": 4.5
    }
}, 

{
    "movie": {
        "title": 'The Joker',
        "director": 'Todd Phillips',
    },
    
    "details": {
        "year": 2019,
        "rating": 4.7
    }
}
}]

I want to map the response to xml which I have the following function for

function mapToMoviesXML(movies: Movie[]) {
  let data = `<?xml version="1.0" encoding="UTF-8"?>`;
  data  = `<movies>`;
  for (let item of movies) {
    data  = `<movies>
           <title>${item.movie.title}</title>
           <director>${item.movie.director}</director>
           <year>${item.details.year}</year>
           <rating>${item.details.rating}</rating>
        </movies>`;
  }

however, I get the following error for item.movie and item.details within the loop

Property 'movie' does not exist on type 'Movie'
Property 'details' does not exist on type 'Movie'

I thought because I am getting the final value i.e. item.movie.title which is defined in the Movie type I would not need to declare a type for item. Any ideas what I need to change or update my type to?

CodePudding user response:

To satisfy the way movies: Movie[] is being used (and to mirror what the API is actually sending) the type definition would need to be something along the lines of this:

export type Movie = {
  movie: {
    title: string;
    director: string;
  }
  details: {
    year: number;
    rating: number;
  };
};

or potentially more useful would be to break the nested objects into their own types and reference them from the parent object, i.e.

export interface MovieOverview {
  title: string;
  director: string;
}

export interface MovieDetails {
  year: number;
  rating: number;
}

export interface Movie {
  movie: MovieOverview;
  details: MovieDetails;
}
  • Related