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

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

问题描述

我有一些使用对象作为字典的 JavaScript 代码;例如,person"对象将包含一些从电子邮件地址中删除的个人详细信息.

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>];"

是否可以在 Typescript 中对此进行描述?还是我必须使用数组?

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

推荐答案

在较新版本的打字稿中,您可以使用:

In newer versions of typescript you can use:

type Customers = Record<string, Customer>

在旧版本中,您可以使用:

In older versions you can use:

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天全站免登陆