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?
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 .
KeyString ( _KeyCode_ , _KeyCode2_ ) expression A variable that represents an Application object.
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!
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.
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.
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With