
在这篇博文中,通过实例来学习typescript中的字典。
Dictionary是一种无序列表数据的数据结构,包含键和值。它与typecript中的map类型相同。
如何使用地图声明和初始化一个字典?
有多种方法可以创建一个 dictionary:
- 使用map类型 map是ES6和typescript中引入的一种类型。下面的例子包含
- 声明并创建一个 map 变量
- 添加 key-value 对
- 检查键是否存在
- 获取带有键的值
- 删除一个键和它的值
- 用键和值对地图进行迭代
- 从一个地图中删除所有元素
- 获取地图中的元素数量
- 以插入顺序检索所有的键和值
let employees = new Map();
employees.set("name", "john");
// Checking for the key exist :
employees.has("name"); // true
// get a value by a key:
employees.get("name"); // john
// delete an item by a key:
employees.delete("name");
// iterate key and values
employees.forEach((item, key) => console.log(item));
// remove all from map:
employees.clear();
// size:Number of elements in Map :
console.log(employees.size)
// get All keys with insertion order
let keys = Array.from(employees.keys());
// Extract values with insertion order
let values = Array.from(employees.values());
如何为 dictionary 声明一个接口?
在 typescript 中使用可索引类型声明一个接口
声明一个接受key为字符串和value为T类型的接口。
interface Dictionary {
[Key: string]: T;
}
一个类包含字典接口的属性,如下所示。
export class AllEmployees {
employees: Dictionary = {};
}
字典接口用let关键字声明,并初始化值,添加值。
let emps: Dictionary = {};
emps["name"] = "john";
如何用记录类型声明一个字典
记录是一个键和值对的映射。
用type alias(type keyword)和Record类型创建一个新的类型。
type emps = Record
使用对象语法初始化数据,如下所示。
let emps: Record = {
{"name": "john" },
{"id": "1" }
};
总结
通过多个例子学习了在typescript中声明字典类型的typescript字典