- Mapped Types
- Conditional Types
- Template Literal Types
- Typescript array map type
- # Table of Contents
- # Initialize and Type a Map using an Array
- # Initialize and Type a Map using an Object
- # Typing a Map with values of type array
- # Declaring an empty typed Map in TypeScript
- Declare Map or List Type in TypeScript
- Declare Record and Map Type in TypeScript
Mapped Types
When you don’t want to repeat yourself, sometimes a type needs to be based on another type.
Mapped types build on the syntax for index signatures, which are used to declare the types of properties which have not been declared ahead of time:
A mapped type is a generic type which uses a union of PropertyKey s (frequently created via a keyof ) to iterate through keys to create a type:
In this example, OptionsFlags will take all the properties from the type Type and change their values to be a boolean.
There are two additional modifiers which can be applied during mapping: readonly and ? which affect mutability and optionality respectively.
You can remove or add these modifiers by prefixing with — or + . If you don’t add a prefix, then + is assumed.
In TypeScript 4.1 and onwards, you can re-map keys in mapped types with an as clause in a mapped type:
ts
type MappedTypeWithNewPropertiesType> =[Properties in keyof Type as NewKeyType]: Type[Properties]>
You can leverage features like template literal types to create new property names from prior ones:
You can filter out keys by producing never via a conditional type:
You can map over arbitrary unions, not just unions of string | number | symbol , but unions of any type:
Mapped types work well with other features in this type manipulation section, for example here is a mapped type using a conditional type which returns either a true or false depending on whether an object has the property pii set to the literal true :
Conditional Types
Create types which act like if statements in the type system.
Template Literal Types
Generating mapping types which change properties via template literal strings.
The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤
Typescript array map type
Last updated: Jan 20, 2023
Reading time · 3 min
# Table of Contents
# Initialize and Type a Map using an Array
Use the Map() constructor to initialize a Map in TypeScript.
The constructor takes an array containing key-value pair arrays, where the first element is the key and the second is the value.
Copied!// ✅ Initialize Map from Array // 👇️ const map1: Map const map1: Mapstring, string> = new Map([ ['name', 'Bobby Hadz'], ['country', 'Chile'], ]); // 👇️ Map(2) < 'name' =>'Bobby Hadz', 'country' => 'Chile' > console.log(map1);
The Map() constructor takes an array whose elements are key-value pairs.
The first type we passed to the Map generic when initializing the Map is the key, and the second is the value.
We created a Map that has a key and a value of type string in the examples.
# Initialize and Type a Map using an Object
You can use the Object.entries() method if you need to initialize a type a Map using an object.
Copied!const obj = name: 'Bobby Hadz', country: 'Chile' >; const map1 = new Mapstring, string>(Object.entries(obj)); // 👇️ Map(2) < 'name' =>'Bobby Hadz', 'country' => 'Chile' > console.log(map1);
The Object.entries method returns a two-dimensional array, where the nested arrays contain 2 elements — the key and the value.
Copied!const obj = name: 'Bobby Hadz', country: 'Chile' >; // 👇️ [ [ 'name', 'Bobby Hadz' ], [ 'country', 'Chile' ] ] console.log(Object.entries(obj)); // 👇️ const map1: Map const map1 = new Mapstring, string>(Object.entries(obj)); // 👇️ Map(2) < 'name' =>'Bobby Hadz', 'country' => 'Chile' > console.log(map1);
This is a perfect match because the Map() constructor expects an array containing nested arrays of key-value pairs.
# Typing a Map with values of type array
Here is an example where we set the type of the keys in the Map to string and the type of the values to string[] .
Copied!// 👇️ const map1: Map const map1: Mapstring, string[]> = new Map([ ['colors', ['blue', 'red', 'green']], ['languages', ['english', 'spanish', 'german']], ]); // ✅ Get value from Map // 👇️ ['blue', 'red', 'green'] console.log(map1.get('colors')); // ✅ Iterate over Map map1.forEach((value, key) => console.log(value, key); >); // ✅ Check if a key exists in Map console.log(map1.has('colors')); // 👉️ true // ✅ Set a new key in Map map1.set('countries', ['UK', 'Spain', 'Germany']);
The code snippet shows some of the methods the Map object implements.
Now that we’ve set the type of the values in the Map to string[] , we wouldn’t be able to set a value of a different type in the Map .
Copied!// 👇️ const map1: Map const map1: Mapstring, string[]> = new Map([ ['colors', ['blue', 'red', 'green']], ['languages', ['english', 'spanish', 'german']], ]); // ⛔️ Error: Argument of type 'number' is not // assignable to parameter of type 'string[]'. map1.set('age', 30);
We tried to add a new element to the Map with a value of number and TypeScript errored out.
Note that you don’t have to add key-value pairs to a Map when creating it.
Want to learn more about using a Map object in TypeScript ? Check out these resources: How to Iterate over a Map in TypeScript ,Define a Map with Array values in TypeScript.
# Declaring an empty typed Map in TypeScript
You can initialize an empty Map , set its type and add key-value pairs later on in your code.
Copied!// 👇️ const map1: Map const map1: Mapstring, string[]> = new Map([]); map1.set('colors', ['blue', 'red', 'green']); map1.set('languages', ['english', 'spanish', 'german']); // 👇️ ['blue', 'red', 'green'], // 'languages' => ['english', 'spanish', 'german'] // > console.log(map1);
The code sample declares an empty, typed Map that has string keys and arrays containing strings as values.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Declare Map or List Type in TypeScript
- Declare Record and Map Type in TypeScript
- Declare List Type in TypeScript
Maps and lists are the basic data structures used in every programming language for writing application logic. A map is used to quickly retrieve data items from a store, while a list is a data structure where data items are stored sequentially.
TypeScript on its own does not support Map or List types; however, it is very easy to create the required Types using the built-in types in TypeScript.
Declare Record and Map Type in TypeScript
TypeScript has introduced the Record type, which can support map types with key-value pairs and has generic types for supporting maps of different types.
More specifically, Record denotes that an object accepts keys of only type K , and the values corresponding to the keys should be of type V .
key of Record would yield K as the type, and Record[K] is equivalent to V. The Record type is an alias for index signatures like < [ key : K] : V >.
const colorMap : Recordstring, string> = 'ylw' : 'yellow', 'blk' : 'black', 'bl' : 'blue' >;
Thus using the generic types, we can have multiple types for the Map or Record type in TypeScript. After compilation and the following typed object becomes a simple object in JavaScript.
Apart from the typed object, native Javascript has the Map function, which can initialize a new Map instance. It has quite of supported functions associated with it.
The following code segment will demonstrate how the Map function can be used to initialize a new Map object.
const colorMap = new Mapstring, string>(); colorMap.set("ylw", "yellow"); colorMap.set("blk", "black"); colorMap.forEach( ( v, k , _) => console.log( "key : " + k + ", value : " + v); >) // keys var keyList : string[] = [. colorMap.keys()]; console.log(keyList); // values var valueList : string[] = [. colorMap.values()]; console.log(valueList);