Rob*_*lor 316 arrays dictionary object typescript
我有一些JavaScript代码使用对象作为字典; 例如,"人"对象将保留一些键入电子邮件地址的个人详细信息.
var people = {<email> : <'some personal data'>};
adding > "people[<email>] = <data>;"
getting > "var data = people[<email>];"
deleting > "delete people[<email>];"
Run Code Online (Sandbox Code Playgroud)
是否有可能在Typescript中描述这个?还是我必须使用数组?
Rya*_*ugh 513
当然:
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
Run Code Online (Sandbox Code Playgroud)
如果您不想每次都输入整个类型注释,也可以创建一个接口:
interface StringToCustomerMap {
[email: string]: Customer;
}
var map: StringToCustomerMap = { };
// Equivalent to first line of above
Run Code Online (Sandbox Code Playgroud)
Joh*_*isz 114
除了使用类似地图的对象之外,还有一段时间的实际Map对象,在编译为ES6时,或者在使用带有ES6 类型定义的polyfill时,可以在TypeScript中使用:
let people = new Map<string, Person>();
Run Code Online (Sandbox Code Playgroud)
它支持相同的功能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");
Run Code Online (Sandbox Code Playgroud)
仅使用这一点与使用类似地图的对象相比有几个优点,例如:
Object(不,Object不支持数字,它将它们转换为字符串)--noImplicitAny,因为它Map总是具有键类型和值类型,而对象可能没有索引签名Object此外,一个Map对象为常见任务提供了一个更强大和更优雅的API,其中大部分都不能通过简单Object的方式获得而不会将帮助函数混合在一起(尽管其中一些需要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());
Run Code Online (Sandbox Code Playgroud)
小智 76
您可以使用如下模板化界面:
interface Map<T> {
[K: string]: T;
}
let dict: Map<number> = {};
dict["one"] = 1;
Run Code Online (Sandbox Code Playgroud)
您还可以在typescript中使用Record类型:
export interface nameInterface {
propName : Record<string, otherComplexInterface>
}
Run Code Online (Sandbox Code Playgroud)
您可以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' }
}
Run Code Online (Sandbox Code Playgroud)
现在以接口作为值:
interface Icon {
Name: string
Color: string
}
用法:
const icon: SemanticIcon = iconMapping[appointment.Status]
Lodash有一个简单的Dictionary实现,并且具有良好的TypeScript支持
安装Lodash:
npm install lodash @types/lodash --save
Run Code Online (Sandbox Code Playgroud)
进口和使用:
import { Dictionary } from "lodash";
let properties : Dictionary<string> = {
"key": "value"
}
console.log(properties["key"])
Run Code Online (Sandbox Code Playgroud)