打字稿 - 创建复杂的对象
问题描述:
以下变量包含对象的列表的接口:打字稿 - 创建复杂的对象
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
}
}
}
};
如何我可以声明为这种变量的接口?
答
你可以声明为场景的类型:
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
}
}
}
};
'sky'和'blue_area'是可以通过任何其他替代的名字,我的意图是使该密实任何其他名称的东西一般。 – TheUnreal
那么,在这种情况下,你可以用'[key:string]'替换'[key in ScenceNames]?'。 –