【问题标题】:In typescript what does it means to have an object property like this "{ [x: string]: any }"?在打字稿中,拥有像这样“{ [x: string]: any }”这样的对象属性意味着什么?
【发布时间】:2016-01-18 07:12:01
【问题描述】:
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 类型并且它的 indexstring 类型并且 返回值any 类型,那么它如何接受 indexnumber 类型并且 value 类型字符串?

TypeScript 版本:1.6.2

Visual Studio 代码版本:0.9.1

【问题讨论】:

  • 你能把你的问题改进得更具体吗?听起来您在 Typescript 编译器中所做的更改遇到了问题,但在您提供有关您正在使用的 Typescript 版本以及您想要实现的目标的更多详细信息之前,我们不会帮不上忙。

标签: javascript typescript visual-studio-code types


【解决方案1】:

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

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

声明的意思是:你可以给变量x分配一个具有数字属性id的对象,如果你访问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 索引出于同样的原因是有效的(尽管我希望这里只允许使用字符串索引)。

【讨论】:

  • thanx,但是当我尝试写这个 x : { id : number, [ x : string ] : string }; VS Code 报错这一行有什么问题?
  • 好吧,因为id 必须是一个数字,而在JavaScript 中写x.idx['id'] 是一样的
  • [x: string]: string 暗示id.x 必须是一个字符串。
【解决方案2】:

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

这些被称为索引签名。它们在TSLang Handbook 中进行了介绍。

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

【讨论】:

  • 我的问题是作为一个对象属性,它可以做什么?我们如何为其赋值。
猜你喜欢
  • 2011-01-17
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-03
相关资源
最近更新 更多