首页 > 解决方案 > 在 Typescript 中为数组定义接口

问题描述

我还不熟悉 Typescript,我在定义一个简单的数组时遇到了麻烦。

我的目标是有一个数组,其中键是一个字符串,它的值是Sound类型。

我已经定义了一个这样的接口:

interface SoundsArrayType {
    [key: string]: Sound;
}

然后:

class SoundManager {
    private sounds: SoundsArrayType;

    constructor() {
      // error: Type 'undefined[]' is not assignable to type 'SoundsArrayType'.
      if(!this.sounds) this.sounds = [];
    }

    pauseAll() {
        for(let sound of this.sounds) {
            // error: Type 'SoundsArrayType' must have a '[Symbol.iterator]()' method that returns an iterator.
            sound.pause();
        }
    }
}

我不确定如何解决这些错误。我从 Typescript 网站阅读了Interfaces 页面,但我仍然卡住了。

标签: typescript

解决方案


我的目标是有一个数组,其中键是一个字符串,它的值是 Sound 类型。

这可能是 type 的一个很好Map用途

这是在 TypeScript 中。

type Sound = {
    name: string;
};

const myMap = new Map<string, Sound>();
myMap.set('dog', { name: 'woof' });
myMap.set('cat', { name: 'meow' });
myMap.set('fox', { name: 'what does the fox say?!?!' });

这是在没有类型检查的 JavaScript 中。

const myMap = new Map();

myMap.set('dog', { name: 'woof' });
myMap.set('cat', { name: 'meow' });
myMap.set('fox', { name: 'what does the fox say?!?!' });

for (let value of myMap.values()) { 
    console.log(value.name);
}

for (let key of myMap.keys()) { 
    console.log(key);
}

for (let [key, value] of myMap) { 
    console.log(key + ':' + value.name);
}


推荐阅读