Skip to content

Const Enum undefined when imported from remote npm package in create-react-app project #25441

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
stephenkiers opened this issue Jul 4, 2018 · 2 comments

Comments

@stephenkiers
Copy link

TypeScript Version: 3.0.0-dev.20180704

Search Terms: enum, npm, yarn, import, create react app

Reproduction Github Repository
https://github.com/stephenkiers/TypescriptRepo1

Remote Package Code

export const enum TEST {
    MAJOR = "major",
    MINOR = "minor"
}

Target Package Code

type IFoo = {
    type: TEST.MINOR|TEST.MAJOR;
    name: string;
};
const foo: IFoo = {
    type: TEST.MINOR,
    name: "Full Name"
};
console.log(foo.type === TEST.MINOR ? foo.name : "World")

Expected behavior:
Target Package should print Full Name

Actual behavior:
TEST is undefined, so there is Uncaught TypeError: Cannot read property 'MINOR' of undefined

Playground Link:
Cannot recreate in playground, but made public github repo and youtube video

Related Issues: not really, but here are some possible similar issues

@AlCalzone
Copy link
Contributor

Why does it need to be a const enum? From the docs:

Const enums can only use constant enum expressions and unlike regular enums they are completely removed during compilation. Const enum members are inlined at use sites.

As such, this code

namespace foo {
    export const enum TEST {
        MAJOR = "major",
        MINOR = "minor"
    }
}

const bar = foo.TEST.MAJOR;

gets transpiled to

var bar = "major" /* MAJOR */;

If you remove the const modifier from the enum, you get what you expect:

var foo;
(function (foo) {
    var TEST;
    (function (TEST) {
        TEST["MAJOR"] = "major";
        TEST["MINOR"] = "minor";
    })(TEST = foo.TEST || (foo.TEST = {}));
})(foo || (foo = {}));
var bar = foo.TEST.MAJOR;

@stephenkiers
Copy link
Author

The reason we used const enum is we wanted the code inlined at runtime; and it worked when the code was within the same repo. The issue, as it turns out, is that the create-react-app-typescript project does not compile code in /node_modules/ properly.

I will look into fixing that, to see if I can get this working properly.

As it seems that the issue is not typescript, I am closing this issue for now.

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants