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

标签 javascript types typescript

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

{
  'id': 1,
  'attr1': 124,
  'attr2': 4356,
  ...
}

?

我搜索了 http://www.typescriptlang.org/Handbook并发现,我可以像这样使用数组类型(键和值):

interface StringArray {
  [index: number]: string;
}

但实际上,Map(JS 对象)和 Array 在概念上并不相同(在 JavaScript 中,它们的行为相似,但在 TypeScript 中,由于强类型,应分开处理)。

最佳答案

is it possible to specify allowed values in an Object? E.g. to specify that all keys should have numbers

是的,这是可能的。

在 JavaScript 和 TypeScript(它是 JS 的超集)中,您可以通过 obj.propobj['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
};

Above example in TS Playground

关于javascript - typescript 强类型 - 指定对象值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31985027/

相关文章:

javascript - Meteor:通过电子邮件发送文档 ID

javascript - 未从 JSON 加载网格数据

Haskell:模式匹配类型注释中需要ScopedTypeVariables

mysql - mysql中的float精度问题

javascript - 数组元素子类型

javascript - 字符串转正则表达式

javascript - for循环内的jQuery自定义事件仅在最后一次迭代时触发

c++ - Windows 编程和数据类型

typescript :导出具有不同名称的相同功能

javascript - JS 到 TS : Type 'null' is not assignable to type 'number'