TypeScript - 为复杂对象创建接口

时间:2017-06-03 16:08:27

标签: angular typescript interface

以下变量包含对象列表:

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
        }
      }
    }
};

如何为这种变量声明接口?

1 个答案:

答案 0 :(得分:1)

您可以将场景类型声明为:

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
        }
      }
    }
};