【问题标题】:Using static properties with typescript, node, and babel使用 typescript、node 和 babel 的静态属性
【发布时间】:2016-09-18 19:46:55
【问题描述】:

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

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"]
}

知道可能是什么错误吗?转译后的代码应该看起来不同(即我的 typescript 配置有问题)还是我缺少另一个 babel 插件?

【问题讨论】:

    标签: javascript node.js typescript babeljs


    【解决方案1】:

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

    Spec for property name of Function instances

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

    老实说,最好避免将 namelengthprototype 作为静态类属性。

    【讨论】:

    • 非常感谢,@MinusFour!
    猜你喜欢
    • 2016-10-10
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    相关资源
    最近更新 更多