嗨,我在Typescript中有界面:
interface sprite_loading {
[index: number]: {
URL: string,
name: string
}}
我正在类中创建一个数组:
public spriteLoading: sprite_loading;
但是当我尝试使用每个数组时:
private preload() {
var phaser = this;
this.spriteLoading.forEach(function (element) { //here is the problem
phaser.game.load.image(element.name, element.URL);
});
}
我收到此错误,但代码有效。
engine.ts:57:28 - error TS2339: Property 'forEach' does not exist on type 'sprite_loading'.
为什么会出现此错误?我确定spriteLoading是一个数组。
答案 0 :(得分:2)
如果您依赖数组,则可以免费获取它的定义。示例:
interface sprite_loading extends Array<{ URL: string, name: string}> {
[index: number]: {
URL: string,
name: string
}
}
let example: sprite_loading = [
{ URL: 'foo', name: 'foo' },
{ URL: 'bar', name: 'bar' },
{ URL: 'baz', name: 'baz' }
];
example.forEach((val) => console.log(val.URL));
如果您的sprite_loading
界面不是特别时髦,您可能更喜欢定义每个条目的类型,因为它们更简洁:
type Sprite = { URL: string, name: string, things: Thing[] };
let example: sprite_loading = [
{ URL: 'foo', name: 'foo' },
{ URL: 'bar', name: 'bar' },
{ URL: 'baz', name: 'baz' }
];
这是定义其他数组成员的一种巧妙方法:
type Thing = { thingness: number };
type Sprite = { URL: string, name: string, things: Thing[] };
let example: Sprite[] = [
{ URL: 'foo', name: 'foo', things: [{ thingness: 5}, { thingness: 8}] },
{ URL: 'bar', name: 'bar', things: [] },
{ URL: 'baz', name: 'baz', things: [] }
];
example.forEach((val) => console.log(val.URL));