Robert Taylor Robert Taylor - 1 year ago 137
TypeScript Question

TypeScript Objects as Dictionary types as in C#

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?

Answer Source


var map: { [email: string]: Customer; } = { };
map[''] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map[''] = '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