首页 文章

TypeScript对象作为C#中的字典类型

提问于
浏览
256

我有一些JavaScript代码使用对象作为字典;例如,“人”对象将保留一些键入电子邮件地址的个人详细信息 .

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

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

是否有可能在Typescript中描述这个?还是我必须使用数组?

5 回答

  • 432

    当然:

    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
    
  • 68

    您可以使用如下模板化界面:

    interface Map<T> {
        [K: string]: T;
    }
    
    let dict: Map<number> = {};
    dict["one"] = 1;
    
  • 67

    除了使用类似 Map 的对象之外,现在已经有一段时间了,在编译为ES6时,或者在使用带有ES6 type-definitions的polyfill时,可以在TypeScript中使用Map object

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

    仅使用这一点与使用类似 Map 的对象相比有几个优点,例如:

    • 支持非基于字符串的密钥,例如数字或对象, Object 都不支持这些数字或对象(不, Object 不支持数字,它将它们转换为字符串)

    • 不使用 --noImplicitAny 时错误的空间,因为 Map 始终具有键类型和值类型,而对象可能没有索引签名

    • 添加/删除项目(键值对)的功能针对任务进行了优化,unlike creating properties on an 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());
    
  • 5

    Lodash有一个简单的Dictionary实现,并且具有良好的TypeScript支持

    安装Lodash:

    npm install lodash @types/lodash --save
    

    进口和使用:

    import { Dictionary } from "lodash";
    let properties : Dictionary<string> = {
        "key": "value"        
    }
    console.log(properties["key"])
    
  • 2

    您还可以在typescript中使用Record类型:

    export interface nameInterface { 
        propName : Record<string, otherComplexInterface> 
    }
    

相关问题