22

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?

2

1 Answer 1

28

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.
}; 
Sign up to request clarification or add additional context in comments.

2 Comments

Does this mean that I can add as many new properties as I wish? Could I also add mouse: 'tippy' and car: 'BMW' and still have the variable f in this example be valid?
@Socrates Yup, as long as the extra properties are of type boolean, number or string .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.