Enum inside class (TypeScript definition file)

Lewis Peel picture Lewis Peel · Apr 24, 2015 · Viewed 80.4k times · Source

I've searched around but can't seem to find an answer for this, hopefully you can help.

How can I add an enum to Image? This is what I would like ideally but I get an error.

declare module 'Lib' {
  export module Graphics {
    export class Image {
      enum State {}

      static STATE_IDLE: State;
      static STATE_LOADING: State;
      static STATE_READY: State;
      static STATE_ERROR: State;
      constructor();
    }
  }
}

If I move State into the Graphics module it works but now State belongs to Graphics, which is incorrect. It needs to be part of Image.

Answer

NSjonas picture NSjonas · Dec 1, 2017

I think the following is an improvement on KoenT's solution:

export class Image
{
    constructor ()
    {
        this.state = Image.State.Idle;
    }

    state: Image.State;
}

export namespace Image
{
    export enum State
    {
        Idle,
        Loading,
        Ready,
        Error
    }
}

The advantage being that you can leverage named imports:

import {Image} from './image';
let img = new Image()
img.state = Image.State.Error