1

I have the following module defined in Typescript

declare module MyTypes {

    export enum MyEnum {
        GOOD = 'Good',
        BAD = 'Bad',
        UNKNOWN = '-'
    }

   export interface MyType1 {
      myType1:string
   }

}

export default MyTypes;

In a separate file, I import it like so:

import MyTypes from '/my-types'
import MyType1 = MyTypes.MyType1
import MyEnum = MyTypes.MyEnum

When I refer in the code to MyEnum.GOOD, Chrome returns an exception on the console MyTypes is not defined. What is the appropriate way to import enums from modules in typescript?

1 Answer 1

6

When using declare, typescript does not create any javascript code, it only implies that it already exists. With interfaces it all should work well, because they are just stripped at runtime. An enum on the other hand has actual string values like "Good".

You can simply remove the declare keyword and it all should work.

module MyTypes {

    export enum MyEnum {
        GOOD = 'Good',
        BAD = 'Bad',
        UNKNOWN = '-'
    }

   export interface MyType1 {
      myType1:string
   }

}

export default MyTypes;

FYI your enum in javascript would look like this:

export var MyEnum;
(function (MyEnum) {
    MyEnum["GOOD"] = "Good";
    MyEnum["BAD"] = "Bad";
    MyEnum["UNKNOWN"] = "-";
})(MyEnum || (MyEnum = {}));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, is there a reference about this I could read for learning?
@Edmondo1984 you can read about declaration files in here typescriptlang.org/docs/handbook/declaration-files/… thats the only place to use declare

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.