Búsqueda de sitios web

javascript - Cómo definir un hash con claves de enumeración en Typescript


Estoy haciendo un emulador de máquina RAM en TypeScript, así que hice un enum de los tipos de instrucciones que puede tener una RAM:

enum InsType {
    LOAD,   // Put value from specified register (or literal) into accumulator.
    STORE,  // Store value from accumulator into specified register.
    READ,   // Read from input tape and write into specified register.
    WRITE,  // Write to output tape from specified register.
    ADD,    // Add value into accumulator.
    SUB,    // Subtract value from accumulator.
    MUL,    // Multiply accumulator by referenced (or literal) value.
    DIV,    // Divide accumulator by referenced (or literal) value.
    HALT,   // Stop program execution.
    JUMP,   // Jump unconditionally to line specified by tag.
    JZERO,  // Jump to line specified by tag if accumulator value is zero.
    JGTZ,   // Jump to line specified by tag if acc value is greater than zero.
}

Tengo que asegurarme de que cada instrucción tenga un tipo de operando válido. Mi manera de definir los operandos válidos es así:

var valid_operands = {
  LOAD:   [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT],
  STORE:  [                    OpType.NUM_DIRECT, OpType.NUM_INDIRECT],
  READ:   [                    OpType.NUM_DIRECT, OpType.NUM_INDIRECT],
  WRITE:  [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT],
  ADD:    [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT],
  SUB:    [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT],
  MUL:    [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT],
  DIV:    [OpType.NUM_LITERAL, OpType.NUM_DIRECT, OpType.NUM_INDIRECT],
  HALT:   [OpType.NONE],
  JUMP:   [OpType.NAME],
  JZERO:  [OpType.NAME],
  JGTZ:   [OpType.NAME],
}

Pero encuentro que el 'compilador' de TypeScript no se preocupa por lo que pongo en los valores de las claves: puedo cambiar LOAD: a LOADXYZ: y no parpadeará.

Además, cuando intento cambiarlo a esto:

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

Advierte ':' esperado en la línea XX col YY (siendo esa la posición del .). Estoy usando el plugin de TypeScript de Atom para trabajar, si sirve de algo. Se agradece cualquier ayuda.

Respuesta #1

define la clave del objeto dentro de []

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

....

Respuesta #2

Puedes usar Map.

enum InsType {
    LOAD,
    STORE
}

enum OpType {
    NUM_LITERAL
}

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

Respuesta #3

Puedes usar: key in Enum

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

entonces :

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 });

Artículos relacionados