Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript array of key value pairs declaration

Confused about the following declaration:

constructor(controls: {[key: string]: AbstractControl}, optionals?: {[key: string]: boolean}, validator?: ValidatorFn, asyncValidator?: AsyncValidatorFn) 

What is the type of the controls (first parameter)? Is it an object which is an array of key value pairs where key is string and value is AbstractControl? Thanks!

like image 915
mishap Avatar asked Apr 19 '16 21:04

mishap


People also ask

How do you declare an array of key-value pairs in TypeScript?

Use an index signature to define a key-value pair in TypeScript, e.g. const employee: { [key: string]: string | number } = {} . An index signature is used when we don't know all the names of a type's keys ahead of time, but we know the shape of their values.

How do you insert a key-value pair in an array?

To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.

Can array have key-value pairs?

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well. Simple Array eg. We see above that we can loop a numerical array using the jQuery.

How do I map a key-value pair in TypeScript?

To define a Map with array values in TypeScript, type the map to have keys of a specific type and set the values to have an array type, e.g. const map1 = new Map<number, string[]>() . All of the key-value pairs in the Map must conform to the specified type. Copied!


1 Answers

Yes, like you guessed, it's a js object with key as string and AbstractControl as values.
For example:

{     "control1": new Control(),     "control2": new Control() } 

Edit

You can declare a variable to be of this type in two ways:

let controls: { [key: string]: AbstractControl }; 

or

interface ControlsMap {     [key: string]: AbstractControl; }  let controls: ControlsMap; 

or even better:

interface ControlsMap<T extends AbstractControl> {     [key: string]: T; }  let controls1: ControlsMap<AbstractControl>; let controls2: ControlsMap<MyControl>; 
like image 75
Nitzan Tomer Avatar answered Sep 18 '22 04:09

Nitzan Tomer