admin管理员组文章数量:1394764
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,
...
}
?
I've searched through and found out, that I can use Array typing (both keys and values) like this:
interface StringArray {
[index: number]: string;
}
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).
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,
...
}
?
I've searched through http://www.typescriptlang/Handbook and found out, that I can use Array typing (both keys and values) like this:
interface StringArray {
[index: number]: string;
}
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).
Share Improve this question asked Aug 13, 2015 at 9:57 ducinducin 26.5k44 gold badges166 silver badges261 bronze badges1 Answer
Reset to default 8is it possible to specify allowed values in an Object? E.g. to specify that all keys should have numbers
Yes, this is possible.
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
};
Above example in TS Playground
本文标签: javascripttypescript strong typingspecifying object value typesStack Overflow
版权声明:本文标题:javascript - typescript strong typing - specifying object value types - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744102232a2590918.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论