繁体   English   中英

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

[英]Using static properties with typescript, node, and babel

我正在尝试创建一个静态类属性

import 'babel-polyfill';

class Test {
  static name = 'abc';
}

通过打字稿来解析

require("babel-polyfill");

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

现在,当我使用babel-node运行时,我得到了

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

我的babelrc看起来像这样:

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

知道什么可能是错误吗? 如果交叉代码看起来不同(即我的打字稿配置有问题),还是我错过了另一个babel插件?

问题是您为该静态属性选择的名称。 它与函数的属性name (构造函数和类是)是只读的。

Function实例的属性name的规范

从技术上讲, name仍然可以替换,因为该属性是可configurable ,因此可以用Object.defineOwnProperty替换Object.defineOwnProperty 它就是transform-class-properties将静态属性分配给构造函数的方式。 它需要使用Object.defineOwnProperty ,而不仅仅是这样做。

老实说,如果你避免使用namelengthprototype作为静态类属性,那将是最好的。

暂无
暂无

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

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