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
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).
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.
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