【问题标题】:Error when calling super.method() on a method that is defined as an arrow function in Typescript在 Typescript 中定义为箭头函数的方法上调用 super.method() 时出错
【发布时间】:2019-11-08 13:44:11
【问题描述】:

当一个方法在基类中定义为箭头函数时,当通过 super.method() 在派生类中调用该方法时,我收到错误“只有基类的公共和受保护方法可以通过'super' keyword.ts(2340)",即使该方法被定义为公共。

我知道在箭头函数中上下文是词法的。这会影响箭头函数中thissuper的值,但是上图中Sun.met1没有定义为箭头函数,所以我不明白为什么它不能访问Father.met。

【问题讨论】:

  • 这不是编辑器的事情。运行npm run tsc时显示错误
  • 环境:Create-React-App --typescript 模式。 VSCode

标签: typescript create-react-app


【解决方案1】:

您可以通过将 tsconfig.json 中的 targetes5 更改为 es6 或更新来解决此问题:

"target": "es6"

我不确定这是否是设计使然,但我已打开 https://github.com/microsoft/TypeScript/issues/32121 以获得 TS 团队的澄清

或者,只使用普通方法而不是箭头函数

【讨论】:

猜你喜欢
  • 2022-07-07
  • 2014-06-06
  • 2012-11-30
  • 2017-12-13
  • 2022-09-27
  • 2020-07-04
  • 2019-10-06
  • 2022-12-02
  • 1970-01-01
相关资源
最近更新 更多