简体   繁体   English

使用带有typescript,node和babel的静态属性

[英]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 现在,当我使用babel-node运行时,我得到了

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

My babelrc looks like this: 我的babelrc看起来像这样:

{
  "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? 如果交叉代码看起来不同(即我的打字稿配置有问题),还是我错过了另一个babel插件?

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. 它与函数的属性name (构造函数和类是)是只读的。

Spec for property name of Function instances Function实例的属性name的规范

Technically, name can still be replaced because the property is configurable , so it can be replaced with Object.defineOwnProperty . 从技术上讲, name仍然可以替换,因为该属性是可configurable ,因此可以用Object.defineOwnProperty替换Object.defineOwnProperty It's just the way transform-class-properties assigns the static properties to the constructor. 它就是transform-class-properties将静态属性分配给构造函数的方式。 It needs to use Object.defineOwnProperty and not just do the assignment like that. 它需要使用Object.defineOwnProperty ,而不仅仅是这样做。

Honestly, it'd be best if you avoid name , length and prototype as static class properties. 老实说,如果你避免使用namelengthprototype作为静态类属性,那将是最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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