gpt4 book ai didi

typescript - 在 Typescript 中为数组定义接口(interface)

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:24 24 4
gpt4 key购买 nike

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

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

我定义了一个这样的接口(interface):

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

我不确定如何修复这些错误。我读了Interfaces page来自 Typescript 网站,但我仍然卡住了。

最佳答案

My goal is to have an array where the key is a string and its values are of types Sound.

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

这是在 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);
}

关于typescript - 在 Typescript 中为数组定义接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56159481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com