Skip to content

v7 plugin-proposal-class-properties transform flow type annotation to undefined #8417

@allex

Description

@allex

Bug Report

Current Behavior

@babel/plugin-proposal-class-properties transform flow type annotation to a property assigning undefined.

this may caught statement order unexpected error.

Input Code

let code = `
class B {}
class Logger extends B {
  log: {
    error: boolean
  }
  silent: boolean
  log = {
    error: true
  }
  get silent(): boolean {
    return this._silent;
  }
  set silent(val: boolean) {
    this._silent = !!val;
    if (!this.log) {
      throw new Error('#log should not be nil.')
    }
    Object.keys(this.log).forEach(k => { /* do something... */  })
  }
  constructor() {
    super()
  }
}
`

let r = require("@babel/core").transform(code, {
  "presets": [ "@babel/preset-flow" ],
  "plugins": [
    [ "@babel/plugin-proposal-class-properties", { "loose": true } ]
  ]
})
console.log(r.code)

ouput =>

class B {}

class Logger extends B {
  get silent() {
    return this._silent;
  }

  set silent(val) {
    this._silent = !!val;

    if (!this.log) {
      throw new Error('#log should not be nil.')   // <----- will throw if the annotation property assigning undefined
    }

    Object.keys(this.log).forEach(k => { /* do something... */ });
    });
  }

  constructor() {
    super();
    this.log = void 0;  <<<<<----
    this.silent = void 0; <<<<<---- with setter defined.
    this.log = {
      error: true
    };
  }
}

Expected behavior/code

class B {}

class Logger extends B {
  get silent() {
    return this._silent;
  }

  set silent(val) {
    this._silent = !!val;

    if (!this.log) {
      throw new Error('#log should not be nil.')
    }

    Object.keys(this.log).forEach(k => { /* do something... */ });
  }

  constructor() {
    super();
    this.log = {
      error: true
    };
  }

}

Environment

  • Babel version(s): [e.g. v6.0.0, v7.0.0-beta.55]
  • Node/npm version: [e.g. Node 8/npm 5]
  • OS: [e.g. OSX 10.13.4]
  • Monorepo [e.g. yes/no/Lerna]
  • How you are using Babel: js

Possible Solution

Should strip the ClassProperty type of TypeAnnotation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    outdatedA closed issue/PR that is archived due to age. Recommended to make a new issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions