在打字稿中,拥有像“{ [x: string]: any }”这样的对象属性意味着什么?

Asi*_*han 3 javascript types typescript visual-studio-code

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
Run Code Online (Sandbox Code Playgroud)

如果第二个属性是Array类型并且它的索引string类型并且返回值any类型,那么它如何接受索引number类型并且valuestring类型?

打字稿版本:1.6.2

Visual Studio 代码版本:0.9.1

Mar*_*cka 8

假设我们有这个变量声明:

var x : { 
    id: number, 
    [index: string]: number  // This is not an object property! Note the brackets.
}; 
Run Code Online (Sandbox Code Playgroud)

声明的含义是:您可以将具有数字属性id的对象分配给变量x,如果您通过索引(即)访问x,则返回值必须为 numberx["something"]

所以你可以写:

x.id = 10;    // but not x.id = "Peter";
x["age"] = 20 // but not x["age"] = "old"
Run Code Online (Sandbox Code Playgroud)

现在回到你的例子:

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
Run Code Online (Sandbox Code Playgroud)

fullname在这里是一个有效的对象属性,因为您定义了x可以作为数组访问的属性。奇怪的32是,由于同样的原因,索引也是有效的(尽管我希望这里只允许字符串索引)。


bas*_*rat 5

在打字稿中,拥有这样的对象属性意味着什么{ [x: string]: any }

这些称为索引签名。它们包含在TSLang 手册中

签名[x: string]: any基本上是说使用字符串的任何索引访问的类型是any.