简体   繁体   中英

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 (ie a problem with my typescript config) or am I missing yet another babel plugin?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM