Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 907
Robert Taylor Avatar asked Nov 29 '12 17:11

Robert Taylor


People also ask

What is the type of dictionary in TypeScript?

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.

What is the type of array of objects in TypeScript?

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.

How do I use a key value pair in TypeScript?

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.


1 Answers

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 
like image 199
Ryan Cavanaugh Avatar answered Sep 28 '22 14:09

Ryan Cavanaugh