TypeScript 使用 字典 Dictionary

TypeScript 没有直接的 MapDictionary 类型。不过咱们可使用索引类型模拟它们。html

// key 为 string,value 为 number;
const dic: { [key: string]: number; } = {
    key1: 1,
};

// 添加key,value;
dic['b'] = 2;
dic.c = 3;

// 遍历;
for (const key in dic) {
    if (dic.hasOwnProperty(key)) {
        console.log(dic[key]);
    }
}

关于更多索引类型的内容,能够参考 Ts 文档 高级类型 中的索引类型和字符串索引签名typescript

参考:.net

  1. TypeScript 中使用字典Dictionarycode

  2. 高级类型htm

相关文章
相关标签/搜索