Issue
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
Solution
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).
Answered By - Martin Vseticka
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.