【问题标题】:TypeScript migration: Simplest fix for JavaScript style const definitions generating errors?TypeScript 迁移:JavaScript 样式 const 定义生成错误的最简单修复?
【发布时间】:2016-09-19 09:23:24
【问题描述】:

我正在尝试通过将 .js 文件重命名为 .ts 来将一个中等规模的项目从 JavaScript 迁移到 TypeScript。项目很大,我从小例子开始。 JavaScript 代码已经类似于类,并且我选择了一个简单的类Token 类,开始时没有依赖关系。下面出现了一个简化版本,它的底线使用 tsc 1.8 生成错误,说 "Property 'INVALID_TYPE' does not exist on type () => any."

function Token() {
    this.source = null;
    this.type = null; // token type of the token
    this.line = null; // line=1..n of the 1st character
    this.column = null; // beginning of the line at which it occurs, 0..n-1
    return this;
}

Token.INVALID_TYPE = 0;

我了解如何通过将function Token 转换为class Token,使INVALID_TYPE 成为Token 类的静态成员,但是在近10k 行代码中执行此操作变得相当复杂。我正在寻找一种更渐进的方法。消除错误的一种更简单的方法是将最后一行更改为:

(<any>Token).INVALID_TYPE = 0;

有没有更好的快速修复方法来暂时消除这种 TypeScript 错误信息?

【问题讨论】:

  • 一个真正快速的解决办法是像const Token = &lt;any&gt; function() {... 这样的东西,而不是函数声明。
  • 谢谢@BenSouthgate,非常酷。我如何处理作为Token的子类的类/函数@
  • 撤回那个,我误读了一条错误消息。谢谢。
  • @BenSouthgate,如果您使用 PostYourAnswer 按钮(而不是作为评论)回答,您的回答将获得奖励。

标签: typescript


【解决方案1】:

一个快速的解决方法是将函数声明重写为函数表达式(确保没有提升丢失的问题!)并将其转换为 any 类型,然后您可以添加任何您想要的道具。

const Token = <any> function() {
  // ...
}

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 2021-02-19
    • 2013-05-30
    • 1970-01-01
    • 2020-08-26
    • 2019-06-26
    • 2021-09-23
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多