typescript - 在 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 页面,但我仍然卡住了。
解决方案
我的目标是有一个数组,其中键是一个字符串,它的值是 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);
}
推荐阅读
- r - 我写了一个函数,但它没有给出我期望的输出
- nodes - EJS 中的局部变量
- apache-spark - 具有特定值之前的分析函数
- java - Spring/Java11 - 由于缺少 ServletWebServerFactory bean,无法启动 ServletWebServerApplicationContext
- gitlab - GitLab:所选阶段不存在
- .net-core - 用于协调本地和网络集群的最佳 .Net Actor/Process 框架
- artifactory - 使用 Xray Report API 获取报告 pdf
- python - 一个列表未正确保存在另一个、Python、networkx 中
- javascript - 生成 SHA256 哈希的等效 JavaScript 代码
- java - Tomcat 9 JMX RMI 认证漏洞