1

I have a custom "Enum" interface that that has a value and a description. I've defined an my enum interface like this-

module App {
  export interface IMyEnum {
    [index: string]: IMyEnumValue;
  }

  export interface IMyEnumValue {
      value: any;
      text: string;
  }
}

And my enums like this-

/// <reference path="./enums.interface.ts"/>

module App {
  export const StatusEnum: IMyEnum = {
    Normal: { value: 100, text: 'Normal' },
    Overdue: { value: 200, text: 'Overdue' },
    Critical: { value: 300, text: 'Critical' }
  }
}

But the typescript compiler is complaining that "Normal" does not exist on type IMyEnum.

let statusCode = StatusEnum.Normal.value;

Is there anyway to do this without defining an IStatusEnum interface? I think that would be over-engineering.

1
  • Try putting Normal in "Normal" Commented Feb 9, 2016 at 17:35

1 Answer 1

2

When you cast StatusEnum to IMyEnum, you actually lose type info, leaving you only with an indexer: [index: string]: IMyEnumValue

Option 1: use strings

let statusCode = StatusEnum["Normal"].value;

You'll lose compile-time safety on enum names (e.g. StatusEnum["normal"].value will give a runtime error).

Option 2: get rid of IMyEnum and let the compiler infer the type.

  export const StatusEnum = {
    Normal: { value: 100, text: 'Normal' },
    Overdue: { value: 200, text: 'Overdue' },
    Critical: { value: 300, text: 'Critical' }
  }

let statusCode = StatusEnum.Normal.value;

That way you'll have type safety and autocompletion.

Sign up to request clarification or add additional context in comments.

3 Comments

Guess I can't have my cake and eat it too. Thanks!
Actually, the 2nd option is pretty good in terms of type safety. What is your main reason to declare IMyEnum?
Trying to add some sense to some old code I've adopted. I would have liked to have each object bound by the same rules through the compiler than loosely abiding to them in convention. But this is good enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.