Use enum with TypeScript, with methods on each enumeration

Viewed 2972

I have this TypeScript file:

export type TSumanToString = () => string;

export interface ISumanEvent {
  explanation: string,
  toString: TSumanToString
}

export interface ISumanEvents{
  [key: string]: ISumanEvent
}

export const events: ISumanEvents = Object.freeze({

  // runner events
  TEST_FILE_CHILD_PROCESS_EXITED: {
    explanation: 'runner is started, fires before any test child processes are started.',
    toString: makeToString('TEST_FILE_CHILD_PROCESS_EXITED')
  },

  RUNNER_EXIT_CODE: {
    explanation: 'runner is started, fires before any test child processes are started.',
    toString: makeToString('RUNNER_EXIT_CODE')
  },

  RUNNER_EXIT_SIGNAL: {
    explanation: 'runner is started, fires before any test child processes are started.',
    toString: makeToString('RUNNER_EXIT_SIGNAL')
  },

  RUNNER_HIT_DIRECTORY_BUT_NOT_RECURSIVE: {
    explanation: 'runner is started, fires before any test child processes are started.',
    toString: makeToString('RUNNER_HIT_DIRECTORY_BUT_NOT_RECURSIVE')
  },

  RUNNER_EXIT_CODE_IS_ZERO: {
    explanation: 'runner is started, fires before any test child processes are started.',
    toString: makeToString('RUNNER_EXIT_CODE_IS_ZERO')
  },

  RUNNER_TEST_PATHS_CONFIRMATION: {
    explanation: 'runner is started, fires before any test child processes are started.',
    toString: makeToString('RUNNER_TEST_PATHS_CONFIRMATION')
  },

  // there are a lot more entries

})

this produces a .d.ts file like so:

export declare type TSumanToString = () => string;
export interface ISumanEvent {
    explanation: string;
    toString: TSumanToString;
}
export interface ISumanEvents {
    [key: string]: ISumanEvent;
}
export declare const events: ISumanEvents;

but I need to include each property on events as a constant or an enumeration. I could use an interface to do that, but that would require me to duplicate everything, which seems like a waste.

In other words, I don't want to do this, because this simply duplicates what's in my const, which is a waste, and could easily become out-of-sync:

export interface ISumanEvents {

  TEST_FILE_CHILD_PROCESS_EXITED: ISumanEvent,
  RUNNER_EXIT_CODE: ISumanEvent,
  RUNNER_EXIT_SIGNAL: ISumanEvent,
  RUNNER_HIT_DIRECTORY_BUT_NOT_RECURSIVE: ISumanEvent;
  RUNNER_EXIT_CODE_IS_ZERO: ISumanEvent,
  RUNNER_TEST_PATHS_CONFIRMATION: ISumanEvent

}

is there a way to create a enum so that I don't have to create an interface that just duplicates everything in the actual object?

The problem is I don't know how to define methods on an enum.

1 Answers
Related