简体   繁体   中英

Alternative map definition in Typescript

Today I discovered the Typescript 'map' type and I wanted to use it for declaring a key-value dictionary. 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM