How to define a hash with enum keys in Typescript

You can use: key in Enum

export let MyHashMap: { [key in KeyType]: IMyObject }

sooo:

export enum KeyType {
    A = 'A',
    B = 'B'
}

export interface IMyObject {
    type: KeyType,
    title: string
}

export const MyObject: IMyObject[] = [
    { type: KeyType.A, title: 'my a' },
    { type: KeyType.B, title: 'my b' }
]

//this is the code you want
export let MyHashMap: { [key in KeyType]: IMyObject }


MyHashMap = MyObject.reduce((map, obj) => {
    map[obj.type] = obj;
    return map;
}, {} as { [key in KeyType]: IMyObject });

define the object key inside the []

var valid_operands = {
  [InsType.LOAD]:   [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT],
  [InsType.STORE]:  [                    OpType.NUM_DIRECT, OpType.NUM_INDIRECT],

....


The way I solved it was to assign each key-pair value individually.

var vo2 = { }

vo2[InsType.LOAD]  = [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT]
vo2[InsType.STORE] = [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT]
vo2[InsType.READ]  = [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT]
vo2[InsType.WRITE] = [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT]
vo2[InsType.ADD]   = [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT]
vo2[InsType.SUB]   = [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT]
vo2[InsType.MUL]   = [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT]
vo2[InsType.DIV]   = [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT]
vo2[InsType.HALT]  = [OpType.NONE]
vo2[InsType.JUMP]  = [OpType.NAME]
vo2[InsType.JZERO] = [OpType.NAME]
vo2[InsType.JGTZ]  = [OpType.NAME]

It works fine. But if anyone finds a way to just declare a hash with enum keys, please go ahead and post an answer. :)


You can use Map.

enum InsType {
    LOAD,
    STORE
}

enum OpType {
    NUM_LITERAL
}

var vo2 = new Map<InsType, [OpType]>();
vo2.set(InsType.LOAD, [OpType.NUM_LITERAL]);