patterntypescriptCritical
TypeScript Objects as Dictionary types as in C#
Viewed 0 times
objectstypescripttypesdictionary
Problem
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.
Is it possible to describe this in Typescript? or do I have to use an Array?
var people = { : };
adding > "people[] = ;"
getting > "var data = people[];"
deleting > "delete people[];"Is it possible to describe this in Typescript? or do I have to use an Array?
Solution
In newer versions of typescript you can use:
In older versions you can use:
You can also make an interface if you don't want to type that whole type annotation out every time:
type Customers = RecordIn 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 customerYou 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 aboveCode Snippets
type Customers = Record<string, Customer>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 customerinterface StringToCustomerMap {
[email: string]: Customer;
}
var map: StringToCustomerMap = { };
// Equivalent to first line of aboveContext
Stack Overflow Q#13631557, score: 616
Revisions (0)
No revisions yet.