TheUnreal
TheUnreal

Reputation: 24472

TypeScript - Create an interface for complicated objects

The following variable contains a list of objects:

scenes = {
    sky: {
      image: 'assets/1.jpg',
      points: {
        blue_area: {
          x: 1,
          y: 2
        },
      }
    },
    blue_area: {
      image: 'assets/2.jpg',
      points: {
        sky: {
          x: 1,
          y: 2
        }
      }
    }
};

How I can declare an interface for this kind of variable?

Upvotes: 0

Views: 68

Answers (1)

Hoang Hiep
Hoang Hiep

Reputation: 2412

You can declare the type of Scenes as:

type Points = {
  [key: string]: {
    x: number;
    y: number;
  }
}

type Scenes = {
  [key: string]: {
    image: string;
    points: Points;
  }
}

let scenes: Scenes = {
    sky: {
      image: 'assets/1.jpg',
      points: {
        blue_area: {
          x: 1,
          y: 2
        },
      }
    },
    blue_area: {
      image: 'assets/2.jpg',
      points: {
        sky: {
          x: 1,
          y: 2
        }
      }
    }
};

Upvotes: 1

Related Questions