[英]Alternative map definition in Typescript
Today I discovered the Typescript 'map' type and I wanted to use it for declaring a key-value dictionary. 今天,我发现了Typescript的“ map”类型,并想将其用于声明键值字典。 I know I can do it using arrays, but it's just for playing around.
我知道我可以使用数组来做到这一点,但这只是为了玩而已。 What I want to do is to declare a variable to assign an icon class string to an object type, so:
我想做的是声明一个变量,以将图标类字符串分配给对象类型,因此:
iconForObjectType[OBJ_TYPE (number)] ===> icon class (string) iconForObjectType [OBJ_TYPE(数字)] ===>图标类(字符串)
The code is: 代码是:
let iconForObjectType : { [obj_type : number] : string } = {};
iconForObjectType[ObjectTypes.OBJ_COMPUTER] = 'icon_computer';
iconForObjectType[ObjectTypes.OBJ_PRINTER] = 'icon_printer';
iconForObjectType[ObjectTypes.OBJ_SCANNER] = 'icon_scanner';
iconForObjectType[ObjectTypes.OBJ_MONITOR] = 'icon_monitor';
[ ETC ETC ]
This way of defining it is too repetitive. 这种定义方式太重复了。 Is there an easier alternative like the following?
是否有以下更简单的替代方法?
iconForObjectType = [
ObjectTypes.OBJ_COMPUTER : 'icon_computer',
ObjectTypes.OBJ_PRINTER : 'icon_printer',
[ETC]
];
Thanks! 谢谢!
If you're using key-value pairs in a literal then you want the curly brace: 如果您在文字中使用键值对,则需要花括号:
iconForObjectType = {
[ObjectTypes.OBJ_COMPUTER] : 'icon_computer',
[ObjectTypes.OBJ_PRINTER] : 'icon_printer',
// ...
};
After all, it's just an object with numeric keys. 毕竟,它只是带有数字键的对象。
EDIT: 编辑:
Actually these are computed properties so you need the square brackets around the property key names. 实际上,这些是计算所得的属性,因此您需要在属性键名称两边加上方括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.