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