Answers:
在较新版本的打字稿中,您可以使用:
type Customers = Record<string, Customer>
在旧版本中,您可以使用:
var map: { [email: string]: Customer; } = { };
map['foo@gmail.com'] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map['bar@hotmail.com'] = 'x'; // Not OK, 'x' is not a customer
如果您不想每次都键入整个类型注释,也可以创建一个接口:
interface StringToCustomerMap {
[email: string]: Customer;
}
var map: StringToCustomerMap = { };
// Equivalent to first line of above
map
包含两个成员:(<any> Object.prototype).something = function(){}; Customer {}类var map:{[email:string]:Customer;} = {}; map ['foo@gmail.com'] =新的Customer(); for(var i in map){console.log(map [i])}
var map:MapStringTo<Customer> = {};
除了使用MAP- 喜欢的对象,出现了一个实际的Map
对象有一段时间了,对编译器ES6时,或者使用与ES6一个填充工具时,这是打字稿可用类型的定义:
let people = new Map<string, Person>();
它支持与相同的功能Object
,但语法稍有不同:
// Adding an item (a key-value pair):
people.set("John", { firstName: "John", lastName: "Doe" });
// Checking for the presence of a key:
people.has("John"); // true
// Retrieving a value by a key:
people.get("John").lastName; // "Doe"
// Deleting an item by a key:
people.delete("John");
与使用类似地图的对象相比,仅此一项就具有多个优点,例如:
Object
(不,Object
不支持数字,它将数字转换为字符串)--noImplicitAny
,因为Map
始终具有键类型和值类型,而对象可能没有索引签名Object
此外,Map
对象为常见任务提供了更强大,更优雅的API,Object
如果不将辅助函数合并在一起,则大多数对象都无法通过simple来使用(尽管其中一些需要针对ES5目标或更低版本的完整ES6迭代器/可迭代polyfill):
// Iterate over Map entries:
people.forEach((person, key) => ...);
// Clear the Map:
people.clear();
// Get Map size:
people.size;
// Extract keys into array (in insertion order):
let keys = Array.from(people.keys());
// Extract values into array (in insertion order):
let values = Array.from(people.values());
JSON.stringify()
,因此可以用于例如socket.io :(
Map
序列化很有趣。我首先进行序列化之前先转换为键-值对对象,然后再转换(例如的对象{ key: "John", value: { firstName: "John" } }
)。
您可以使用以下模板化接口:
interface Map<T> {
[K: string]: T;
}
let dict: Map<number> = {};
dict["one"] = 1;
let dict: Dictionary<number> = { "one": 1, "two": 2 };
您可以Record
为此使用:
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt
示例(AppointmentStatus枚举和一些元数据之间的映射):
const iconMapping: Record<AppointmentStatus, Icon> = {
[AppointmentStatus.Failed]: { Name: 'calendar times', Color: 'red' },
[AppointmentStatus.Canceled]: { Name: 'calendar times outline', Color: 'red' },
[AppointmentStatus.Confirmed]: { Name: 'calendar check outline', Color: 'green' },
[AppointmentStatus.Requested]: { Name: 'calendar alternate outline', Color: 'orange' },
[AppointmentStatus.None]: { Name: 'calendar outline', Color: 'blue' }
}
现在将接口作为值:
interface Icon {
Name: string
Color: string
}
用法:
const icon: SemanticIcon = iconMapping[appointment.Status]
enum
或class/object
为AppointmentStatus
-或者什么关系呢?
有一个库提供打字稿中的强类型可查询集合。
集合是:
该库称为ts-generic-collections。(GitHub上的源代码)
您可以创建字典并按以下方式查询它:
it('firstOrDefault', () => {
let dictionary = new Dictionary<Car, IList<Feature>>();
let car = new Car(1, "Mercedez", "S 400", Country.Germany);
let car2 = new Car(2, "Mercedez", "S 500", Country.Germany);
let features = new List<Feature>();
let feature = new Feature(1, "2 - Door Sedan");
features.add(feature);
dictionary.add(car, features);
features = new List<Feature>();
feature = new Feature(2, "4 - Door Sedan");
features.add(feature);
dictionary.add(car2, features);
//query
let first = dictionary.firstOrDefault(x => x.key.name == "Mercedez");
expect(first.key.id = 1);
});