TypeScript对象作为C#中的字典类型 [英] TypeScript Objects as Dictionary types as in C#

查看:332
本文介绍了TypeScript对象作为C#中的字典类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用对象作为字典的JavaScript代码;例如个人对象将保留从电子邮件地址中扣除的一些个人资料。

  var people = {< email> ; :< some personal data>}; 

添加> people [< email>] =< data> ;;
获得> var data = people [< email>];
删除> 删除人[< email>];

可以在Typescript中描述这个吗?或者我必须使用数组?

解决方案

当然:

  var map:{[email:string]:Customer; } = {}; 
map ['foo@gmail.com'] = new Customer(); // OK
map [14] = new Customer(); //不行,14不是字符串
map ['bar@hotmail.com'] ='x'; //不行,'x'不是一个客户

你也可以做一个界面,如果你不想每次都输入整个类型的注释:

  interface StringToCustomerMap {
[email:string]:顾客;
}

var map:StringToCustomerMap = {};
//等于上面的第一行


I have some JavaScript code that uses objects as dictionaries; for example a 'person' object will hold a some personal details keyed off the email address.

var people = {<email> : <some personal data'>};

adding   > "people[<email>] = <data>;" 
getting  > "var data = people[<email>];" 
deleting > "delete people[<email>];"

Is it possible to describe this in Typescript? or do I have to use an Array?

解决方案

Sure:

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

You can also make an interface if you don't want to type that whole type annotation out every time:

interface StringToCustomerMap {
    [email: string]: Customer;
}

var map: StringToCustomerMap = { };
// Equivalent to first line of above

这篇关于TypeScript对象作为C#中的字典类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆