AsimRazaKhan
AsimRazaKhan

Reputation: 2202

In typescript what does it means to have an object property like this "{ [x: string]: any }"?

var x: { id: number, [x: string]: any }; // what does second property means?

x = { id: 1, fullname: "Zia" , 32: "Khan" }; // no errors in VS Code v0.9.1

If the second property is of type Array and its index is of type string and the return value is of type any then how can it accepts index is of type number and value is of type string?

TypeScript version: 1.6.2

Visual Studio Code version: 0.9.1

Upvotes: 4

Views: 6663

Answers (2)

basarat
basarat

Reputation: 276057

In typescript what does it means to have an object property like this { [x: string]: any }?

These are called index signatures. They are covered in the TSLang Handbook.

The signature [x: string]: any basically is saying that the type of any index access using a string is any.

Upvotes: 5

MartyIX
MartyIX

Reputation: 28646

Let's say we have this variable declaration:

var x : { 
    id: number, 
    [index: string]: number  // This is not an object property! Note the brackets.
}; 

The meaning of the declaration is: You can assign to variable x an object with numeric property id and if you access x by an index (i.e. x["something"]), the return value has to a number.

So you can write:

x.id = 10;    // but not x.id = "Peter";
x["age"] = 20 // but not x["age"] = "old"

And now back to your example:

var x: { id: number, [x: string]: any }; // what does second property means?
x = { id: 1, fullname: "Zia", 32 : "Khan" }; // no errors in VS Code v0.9.1

fullname is a valid object property here because you defined that x can be accessed as an array. Strangely, the 32 index is valid for the same reason (even though I would expect that only string indices would be allowed here).

Upvotes: 10

Related Questions