typescript - 为什么 ES2015 类不能在 TypeScript 中可靠地转译?

标签 typescript ecmascript-6 web-component custom-element

我最近在 MDN 上偶然发现了以下声明:

Please note that ES2015 classes cannot reliably be transpiled in Babel 6 or TypeScript targeting legacy browsers. You can either use Babel 7 or the babel-plugin-transform-builtin-classes for Babel 6, and target ES2015 in TypeScript instead of legacy.

此声明对于 TypeScript > 3.x.x 来说是否已经过时,或者有人可以解释 TypeScript 转译有哪些缺点吗?

tsconfig.json 中将 target 设置为 ES5 时,除了必须填充更多功能(如预期的那样)之外,我没有注意到问题)。

了解这些问题(如果存在)在处理自定义元素和 Web 组件时非常有帮助。

最佳答案

正如 Custom Element polyfill 的 Github 页面中所解释的那样,自定义元素被定义为 HTMLElement 类的扩展,它需要一个无法用 ES5 Javascript 完美模拟的新 ES6 功能:super()/Reflect。构造():

The spec requires that an element call the HTMLElement constructor. Typically an ES5 style class would do something like HTMLElement.call(this) to emulate super(). However, HTMLElement must be called as a constructor and not as a plain function, i.e. with Reflect.construct(HTMLElement, [], MyCEConstructor), or it will throw.

关于typescript - 为什么 ES2015 类不能在 TypeScript 中可靠地转译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56473285/

相关文章:

javascript - 如何在动态加载的 Typescript 中扩展类

typescript - 在不同的模块中扩大 TypeScript 中的标记/区分联合?

javascript - 如何覆盖 Polymer 2 中的组件功能?

typescript - Vue 属性装饰器上的感叹号代表什么

javascript - 将 typescript 路径别名编译为 NPM 发布的相对路径?

javascript - 类型错误 : undefined is not an object (evaluating 'store.getState' )

javascript - 当 promise 没有任何返回时怎么办?

javascript - 定义 ES6 符号的简洁方法?

polymer - 构造失败 'HTMLElement'

javascript - 动态实例化 Web 组件的方法之间的差异