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?
A collection of key and value pairs is called a dictionary in TypeScript. The dictionary is also referred as a map or a hash. A map can be created by using the type Map and the keyword new. We can store the collection of key value pairs inside a map by creating a map.
Inline Type for Array of Objects in TypeScript The array of objects is defined inside the curly brackets {} . The array of objects can be defined using inline type.
Typescript Key Value Pair Working A key-value pair is based on the structure of Key and value i.e the first step is to store the key value and then associate the value of it in a Value tag. This is done with the help of API where we have the methods set and get a key to store the key.
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['[email protected]'] = new Customer(); // OK map[14] = new Customer(); // Not OK, 14 is not a string map['[email protected]'] = '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 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With