无法分配给只读属性:Typescript + Babel

时间:2016-01-06 22:35:57

标签: typescript webpack babeljs

我在运行时遇到了编译的打字稿问题。我的链是Typescript - > es6模块 - > webpack + babelify。

有问题的文件是

import Registry from "../registry";

class Alert {

    public static name = "alert";

    public static options = {
        template: require("./alert.mustache")
    };
}

Registry.register(Alert);

这是通过es2015插件+ webpack编译到

"use strict";

var _registry = __webpack_require__(14);

var _registry2 = _interopRequireDefault(_registry);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Alert = function Alert() {
    _classCallCheck(this, Alert);
};

Alert.name = "alert";
Alert.options = {
    template: __webpack_require__(16)
};
_registry2.default.register(Alert);
//# sourceMappingURL=alert.js.map

/*****************
 ** WEBPACK FOOTER
 ** alert.js
 ** module id = 15
 ** module chunks = 0
 **/

但执行时会收到此错误:

alert.js:15 Uncaught TypeError: Cannot assign to read only property 'name' of function Alert() {
    _classCallCheck(this, Alert);
}

我尝试了很多不同的方法,但我不明白为什么在类上使用静态属性会导致这个问题。

提前致谢。

2 个答案:

答案 0 :(得分:2)

name属性是reserved property on functions,用于描述函数的名称,即function foo()foo.name === 'foo'。它在EcmaScript规范中定义为只读属性。因此,您编译的代码最终会尝试分配到name函数的Alert属性,该函数是只读的,但这会失败:

var Alert = function Alert() {
    _classCallCheck(this, Alert);
};

// This is not allowed, because
// [[Function]].name is a read-only property.
Alert.name = "alert";

答案 1 :(得分:0)

代码:

f(Something{
    Base: Base{a: "a", b: "b"},
    c:    "c",
})
运行时

无效。您不能编写函数的class Alert { public static name = "alert"; 属性(如果您转换为es5,则该类是什么)。使用name运算符进行类实例检查。

There is an open issue on github to turn this into a compiler error

相关问题