Skip to content
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

fix(parser): allow TS declare readonly fields with initializers #14817

merged 1 commit into from Jul 31, 2022


Copy link

@Josh-Cena Josh-Cena commented Jul 31, 2022

Q                       A
Fixed Issues? Fixes #14812
Patch: Bug Fix?
Major: Breaking Change?
Minor: New Feature?
Tests Added + Pass? Yes
Documentation PR Link
Any Dependency Changes?
License MIT

This aligns Babel's behavior with microsoft/TypeScript#26313 for class fields. Specifically:

if (isConstOrReadonly && !node.type) {
    if (isInvalidInitializer) {
        return grammarErrorOnNode(node.initializer!, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal);
else {
    return grammarErrorOnNode(node.initializer!, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
if (!isConstOrReadonly || isInvalidInitializer) {
    return grammarErrorOnNode(node.initializer!, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);

However, this PR does not attempt to mimic the isInvalidInitializer part, which checks if the initializer is a string/number literal or an enum reference. Doing so "correctly" would likely require type information. Quoting evanw/esbuild@147163e,

To future-proof this in case TypeScript allows more expressions as initializers in the future (such as null), esbuild will allow any expression as an initializer and will leave the specifics of TypeScript's special-casing here to the TypeScript type checker.

Instead, we avoid all errors with declare readonly that don't have a type annotation.

Copy link

babel-bot commented Jul 31, 2022

Build successful! You can test your changes in the REPL here:

@liuxingbaoyu liuxingbaoyu added PR: Bug Fix 🐛 A type of pull request used for our changelog categories pkg: parser area: typescript labels Jul 31, 2022
@JLHwung JLHwung merged commit a5a8a31 into babel:main Jul 31, 2022
37 checks passed
@Josh-Cena Josh-Cena deleted the ambient-readonly-field branch Aug 1, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
area: typescript pkg: parser PR: Bug Fix 🐛 A type of pull request used for our changelog categories
None yet

Successfully merging this pull request may close these issues.

[Bug]: ambient readonly class field declaration should allow literal initializer
4 participants