typescript强类型 - 指定对象值类型

duc*_*cin 2 javascript types typescript

在TypeScript中,是否可以在Object中指定允许的值?例如,指定所有键都应该有数字:

{
  'id': 1,
  'attr1': 124,
  'attr2': 4356,
  ...
}
Run Code Online (Sandbox Code Playgroud)

我通过http://www.typescriptlang.org/Handbook搜索并发现,我可以使用数组输入(键和值),如下所示:

interface StringArray {
  [index: number]: string;
}
Run Code Online (Sandbox Code Playgroud)

但实际上,Map(JS对象)和一个Array在概念上是不一样的(在JavaScript中,它的行为类似,但在TypeScript中,由于强类型,它应该单独处理).

Bro*_*cco 7

是否可以在对象中指定允许的值?例如,指定所有键都应该有数字

是的,这是可能的.

在JavaScript和TypeScript(它是JS的超集)中,您可以通过obj.prop或通过obj['prop']以下语法访问属性来访问属性.

// This defines an interface that only allows values to be numbers
interface INumbersOnly {
  [key: string]: number;
}

// when using it, it will check that all properties are numbers
var x: INumbersOnly = {
  num: 1, // works fine
  str: 'x' // will give a type error
};
Run Code Online (Sandbox Code Playgroud)

以上是TS Playground中的示例