1

I found this expression in a project:

export class MyComponent implements OnInit {
    public field: { [key: number] : string } = something
    ...
}

and I don't know what it means. Can anyone explain this and give me a reference, so I can learn this type of declarations?

2 Answers 2

3

field is an object type (because of the {}) that has a numeric index signature that returns a string. This means that an object assigned to the field can only have numeric keys and the values in the object must be of type string

let field: { [key: number]: string };

field = {
    0: "A",
    //"A": "A", // error key is not numeric
    //0: 0, // error value is not a string
} 

let a = field[0] //a is string

field = ["A", "B"] // arrays are valid as well

You can read more about it here

Sign up to request clarification or add additional context in comments.

2 Comments

@MateutAlin yes, my bad, fixed :)
@MateutAlin no, it's just the name of the index parameter , it can be any name you want, key and name are common choices, but any name will do
3
{ [key: number] : string }

is an anonymous/inline type declaration, it translates to:

interface Anon {
    [key: number]: string;
}

The brackets are declare, that the type of any undeclared additional property in that object has to be of type number and the value of that type must be a string.

{ 1: "foo", 2: "bar" } // valid
{ "1": "foo", "2": "bar" } // invalid

http://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types-and-string-index-signatures

Comments

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.