Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand syntax in TypeScript interface [key: string]

Tags:

typescript

I'm having trouble deciphering a TypeScript syntax I found within an interface declaration here.

interface FormattingOptions {
    tabSize: number;
    insertSpaces: boolean;
    [key: string]: boolean | number | string;
}

Can someone explain me the third parameter of this interface? The one containing [key: string] ...? How is this type of syntax called?

like image 335
Socrates Avatar asked Jun 01 '18 20:06

Socrates


People also ask

What does Key string mean in TypeScript?

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 a key string?

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

How do you define a key-value pair 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. Copied!

How do interfaces work in TypeScript?

In TypeScript, an interface is an abstract type that tells the compiler which property names a given object can have. TypeScript creates implicit interfaces when you define an object with properties. It starts by looking at the object's property name and data type using TypeScript's type inference abilities.


1 Answers

It's an index signature. It means that besides the known properties of the interface, any other properties of type boolean, number or string can be present

interface FormattingOptions {
    tabSize: number;
    insertSpaces: boolean;
    [key: string]: boolean | number | string;
}

let f: FormattingOptions = {
  tabSize: 1,
  insertSpaces: true,
  other: '' // witout the  index signature this would be invalid.
}; 
like image 111
Titian Cernicova-Dragomir Avatar answered Sep 16 '22 18:09

Titian Cernicova-Dragomir