Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the type { [key: string]: boolean; } mean?

Tags:

typescript

Run into such thing lately, a function declaration:

static required(control: AbstractControl): {   [key: string]: boolean; }; 

What is this return value? An object with an arbitrary amount of properties, where each of them is a boolean and has a name, which appears to be a string? It's more of a typescript question I guess, but just in case someone wonders where I found that - it's Angular's Validators class.

like image 758
Leonid Bor Avatar asked Apr 13 '17 15:04

Leonid Bor


People also ask

What does key string ]: mean?

The {[key: string]: string} syntax is an index signature in TypeScript and is used when we don't know all the names of a type's properties ahead of time, but know the shape of the values. The index signature in the examples means that when an the object is indexed with a string , it will return a string .

What is key string?

KeyString ( _KeyCode_ , _KeyCode2_ ) expression A variable that represents an Application object.

What is key of in TypeScript?

keyof is a keyword in TypeScript which is used to extract the key type from an object type.


1 Answers

This is a key/value structure, named index signatures (or previously known as indexable Types) in typescript.

The key is a string and the value is a boolean. For example:

let map : { [key: string]: boolean} = {}; map["foo"] = true; map["bar"] = false; map.foo = true; map["foobar"] = "foo"; // Throws exception map[1] = true; // Curiously doesn't throws exception 

Check this sample on the Typescript Playground.

like image 173
Leonardo Chaia Avatar answered Nov 15 '22 07:11

Leonardo Chaia