typescript 强类型 - 指定对象值类型 [英] typescript strong typing - specifying object value types

查看:29
本文介绍了typescript 强类型 - 指定对象值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

?

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

I've searched through http://www.typescriptlang.org/Handbook and found out, that I can use Array typing (both keys and values) like this:

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

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

but actually, a Map (JS Object) and an Array is not the same, conceptually (in JavaScript, it behaves similarly, but in TypeScript, it should be treated separately because of the strong typing).

推荐答案

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

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'] 访问属性,这允许下面的语法工作.>

In both JavaScript & TypeScript (which is a superset of JS) you can access properties via obj.prop or obj['prop'] which is what allows the syntax below to work.

// 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
};

以上 TS Playground 示例

这篇关于typescript 强类型 - 指定对象值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆