Tim
Tim

Reputation: 13

Using static properties with typescript, node, and babel

I am trying to create a static class property

import 'babel-polyfill';

class Test {
  static name = 'abc';
}

which gets transpilled by typescript to

require("babel-polyfill");

class Test {
}
Test.name = 'abc';

Now when I run this using babel-node, I get

TypeError: Cannot assign to read only property 'name' of function Test()

My babelrc looks like this:

{
  "passPerPreset": true,
  "presets": [
    "react",
    "es2015",
    "stage-0"
  ],
  "plugins": ["transform-class-properties", "syntax-class-properties"]
}

Any idea what could be the error? Should the transpilled code look different (i.e. a problem with my typescript config) or am I missing yet another babel plugin?

Upvotes: 1

Views: 2106

Answers (1)

MinusFour
MinusFour

Reputation: 14423

The problem is the name that you chose for that static property. It conflicts with the property name of functions (which constructors and classes are) which is readonly.

Spec for property name of Function instances

Technically, name can still be replaced because the property is configurable, so it can be replaced with Object.defineOwnProperty. It's just the way transform-class-properties assigns the static properties to the constructor. It needs to use Object.defineOwnProperty and not just do the assignment like that.

Honestly, it'd be best if you avoid name, length and prototype as static class properties.

Upvotes: 6

Related Questions