Skip to content

TypeScript & @babel/plugin-proposal-class-properties -- _defineProperty is called for abstract properties #11542

@KB1RD

Description

@KB1RD

Bug Report

  • I would like to work on a fix! (Maybe... Depends on how involved it is)

Input Code
This issue appears specific to @babel/plugin-proposal-class-properties and TypeScript. Here is the input TypeScript:

abstract class A {
  abstract test: number
}
class B extends A {
  get test(): number {
    return 5
  }
}

console.log(new B().test) // Should be 5
                          // Actually is undefined

Also in this repl.

Current Behavior
The above code compiles into this:

"use strict";

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

class A {
  constructor() {
    _defineProperty(this, "test", void 0);
  }

}

class B extends A {
  get test() {
    return 5;
  }

}

console.log(new B().test); // Should be 5
// Actually is undefined

This code logs undefined into console.

Expected behavior/code
This code should log 5 to the console. Instead, it logs undefined. For any additional information, see the repl.

In plain JS, if a property is declared in a superclass, a getter in the subclass cannot change its value even if it is set to undefined. This leads to the behavior above where undefined is logged. The implication in TS when specifying an abstract property is that the property has no value, not that its value is undefined. When _defineProperty is placed in the resulting code, this sets the value of that property to undefined, which is not consistent with non-Babel TypeScript compilers and leads to the unexpected undefined.

Metadata

Metadata

Assignees

No one assigned

    Labels

    i: needs triageoutdatedA 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