Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums in typescript d.ts file

I'm new to Typescript and I'm using it in a create-react-project. I have a folder called /typings which my tsconfig.json file points to and so far I've put all my type declarations in an index.d.ts file in that folder.

So far so good. "type" and "interface" declarations seem to be available in all parts of my project. I'm not explicitly exporting them from the index.d.ts file and not importing them into any other file.

The problem comes when I declare the following...

enum Gender {male, female}

When I try to use the enum in a different file I get the error...

Ambient const enums are not allowed when the '--isolatedModules' flag is provided

I have read other answers on SO which say you should declare the enum as a const but that doesn't help. I've also seen the suggestion that you should "export defualt undefined" at the bottom of the file but when I do that none of the other types are available in the rest of the project.

Lastly, I have tried changing my compiler options to set "isolatedModules": false but it automatically gets switched back to true when compiling. Apparently create-react-app will always do thi.

What should I do to allow enums declared in my index.d.ts file to be available to use in the rest of my project automatically?

like image 368
jonhobbs Avatar asked May 30 '20 22:05

jonhobbs


1 Answers

Enums can't go into a d.ts.

Reason for this is that enums have a compiled output, where as other .d.ts such as interfaces do not.

For example:

enum Hello{
    One = 'This is one',
    Two = ''
}

compiles to:

"use strict";
var Hello;
(function (Hello) {
    Hello["One"] = "This is one";
    Hello["Two"] = "";
})(Hello || (Hello = {}));

whereas an interface:

interface Hello {
    test: string;
}

compiles to:

// an empty file, as interfaces are only used during pre-compile not in Javascript.

.d.ts files are not explicitly imported into files and so as a result, Typescript does not know where to inject this file contents. As you are most likely aware, Javascript is compiled top to bottom, so where that enum is injected into the output Javascript is critical.

We historically put our enums into a common.ts file & class that we import when you require to use an enum.

like image 55
Zze Avatar answered Oct 09 '22 05:10

Zze