Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import an Enum

Tags:

typescript

I have created an enum, but I am having trouble importing and using the enum in VS15.

This is the enum which is contained in enums.ts:

enum EntityStatus {
     New = 0,
     Active = 1,
     Archived = 2,
     Trashed = 3,
     Deleted = 4
}

Visual Studio sees this enum without even importing and so does not give a compile time error. But at runtime, an error is thrown

 Cannot read property 'Archived' of undefined.

So now I try to import it like I import other classes:

 import {EntityStatus} from "../../core/enums";

Visual Studio now gives a compile time error:

 "...enums is not a module ..."

So how do I import the enum?

like image 458
Greg Gum Avatar asked Jul 24 '16 14:07

Greg Gum


People also ask

Can you import an enum?

In order to be able to import an enum from a different file, it has to be exported using a named or default export.

How do you use enums?

You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”).

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.


4 Answers

I was missing the export keyword:

 export enum EntityStatus {
      New = 0,
      Active = 1,
      Archived = 2,
      Trashed = 3,
      Deleted = 4
 }

Then it worked as expected.

like image 182
Greg Gum Avatar answered Oct 11 '22 03:10

Greg Gum


You will get the same Cannot read property 'Foo' of undefined. runtime error when you happen to define your Enum in one of the TypeScript Declaration files (*.d.ts) as these files does not get transpired into JavaScript.

More details with a sample app can be found here.

like image 33
luk355 Avatar answered Oct 11 '22 01:10

luk355


Kindly try this. It works for me

enums.ts

export enum  Category {Cricket,Tennis,Golf,Badminton}

and in required .ts file import like the way given below:

import {Category} from './enums'
like image 28
Sachin Kalia Avatar answered Oct 11 '22 01:10

Sachin Kalia


Just ran across something similar. In my case, I had to ensure the exported enum name was different than the name of the file.

ie.

export enum AccessMode in file access-mode.ts would fail. export enum AccessMode in file access-modes.ts would work.

like image 22
Darren Yuhar Avatar answered Oct 11 '22 02:10

Darren Yuhar