google / google/closure-compiler

Can't Freeze Enum With Namespace

Open
#3,162 2 comments 0 reactions 0 assignees View on GitHub
triage-done
Dominant language
JavaScript
Stars
7.7k
Forks
1.2k
Avg merge
2d 12h
Merged PRs (30d)
6

Description

Currently this [compiles without warnings](https://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%2540compilation_level%2520ADVANCED_OPTIMIZATIONS%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250Agoog.provide('foo.Animals')%253B%250A%250A%252F**%250A%2520*%2520%2540enum%250A%2520*%252F%250Afoo.Animals%2520%253D%2520%257B%250A%2520%2520DOG%253A%25200%252C%250A%2520%2520CAT%253A%25201%250A%257D%253B%250A%250Aconst%2520DOG%2520%253D%2520foo.Animals.DOG%253B):

```javascript
goog.provide('foo.Animals');

/**
* @enum
*/
foo.Animals = {
DOG: 0,
CAT: 1
};

const DOG = foo.Animals.DOG;
```

But this [has several warnings](https://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%2540compilation_level%2520ADVANCED_OPTIMIZATIONS%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250Agoog.provide('foo.Animals')%253B%250A%250A%252F**%250A%2520*%2520%2540enum%250A%2520*%252F%250Afoo.Animals%2520%253D%2520Object.freeze(%257B%250A%2520%2520DOG%253A%25200%252C%250A%2520%2520CAT%253A%25201%250A%257D)%253B%250A%250Aconst%2520DOG%2520%253D%2520foo.Animals.DOG%253B):

```javascript
goog.provide('foo.Animals');

/**
* @enum
*/
foo.Animals = Object.freeze({
DOG: 0,
CAT: 1
});

const DOG = foo.Animals.DOG;
```

These are the warnings:

```
JSC_TYPE_MISMATCH: assignment to property Animals of foo
found : {CAT: number, DOG: number}
required: enum{foo.Animals} at line 6 character 0
foo.Animals = Object.freeze({
^
JSC_ENUM_INITIALIZER_NOT_ENUM: enum initializer must be an object literal or an enum at line 6 character 0
foo.Animals = Object.freeze({
^
JSC_INEXISTENT_ENUM_ELEMENT: element DOG does not exist on this enum at line 11 character 12
const DOG = foo.Animals.DOG;
```

This can be worked around by freezing the enum after it is initialized, but doing it all in one go is cleaner syntactically.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.