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
如果第二个属性的类型为Array,其索引的类型为string,并且返回值是 any 类型,那么它如何接受 index 类型为 number 且 value 类型为 字符串?
TypeScript 版本:1.6.2
Visual Studio 代码版本:0.9.1
最佳答案
假设我们有这个变量声明:
var x : {
id: number,
[index: string]: number // This is not an object property! Note the brackets.
};
该声明的含义是:您可以将具有数字属性id的对象分配给变量x,并且如果您访问x> 通过索引(即 x["something"]
),返回值必须为数字。
所以你可以写:
x.id = 10; // but not x.id = "Peter";
x["age"] = 20 // but not x["age"] = "old"
现在回到你的例子:
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
在这里是一个有效的对象属性,因为您定义了 x
可以作为数组进行访问。奇怪的是,出于同样的原因,32
索引也是有效的(尽管我希望这里只允许使用字符串索引)。
关于javascript - 在 typescript 中,拥有像这样的对象属性 "{ [x: string]: any }"意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33222885/