TypeScript Objects as Dictionary types as in C#

前端 未结 6 751
春和景丽
春和景丽 2020-11-27 09:39

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.



        
6条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 09:57

    In newer versions of typescript you can use:

    type Customers = Record
    

    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
    

提交回复
热议问题