我有一些JavaScript代码,使用对象作为字典;例如,“person”对象将保存一些个人详细信息,以电子邮件地址为键。
var people = {<email> : <'some personal data'>};
adding > "people[<email>] = <data>;"
getting > "var data = people[<email>];"
deleting > "delete people[<email>];"
是否有可能在Typescript中描述这一点?或者我必须使用数组?
在较新的typescript版本中,您可以使用:
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
在较新的typescript版本中,您可以使用:
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
你可以使用Record:
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt
示例(一个AppointmentStatus enum和一些元数据之间的映射):
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为值:
界面图标{
名称:字符串
颜色:字符串
}
用法:
const icon: SemanticIcon = iconMapping[预约。状态)