【问题标题】:What is the "as syntax" pointed out by tslint?tslint 指出的“as 语法”是什么?
【发布时间】:2017-10-27 09:23:14
【问题描述】:

我升级了 tslint,现在它抱怨:

ERROR: src/Metronome/JobFetcher.ts[13, 32]: Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead.

有问题的代码如下所示:

const jobs = <JobConfig[]> <any> await rp(fetchJobsOptions);

什么是 as 语法,为什么要使用它?

【问题讨论】:

    标签: typescript tslint


    【解决方案1】:

    像这样重构你的代码:

    const jobs = await rp(fetchJobsOptions) as JobConfig[];
    

    正如TypeScript Deep Dive book by Basarat Ali Syed 中所指出的,它谈到了类型转换:

    作为 foo 与 &lt;foo&gt;

    最初添加的语法是&lt;foo&gt;。这证明了 下面:

    var foo: any;
    var bar = <string> foo; // bar is now of type "string"
    

    但是使用时语言语法有歧义

    <foo> style assertions in JSX:
    var foo = <string>bar;
    </string>
    

    因此现在建议您只使用 as foo for 一致性。

    类型断言与强制转换

    之所以不叫“类型转换”是因为 通常意味着某种运行时支持。但是类型 断言纯粹是一个编译时构造,也是一种方法 向编译器提供有关您希望代码如何的提示 分析。

    【讨论】:

      【解决方案2】:

      如果你想抑制错误,你也可以去tslint.json并包含

      ...
      "rules": {
          "no-angle-bracket-type-assertion": false,
          ...
      }
      ...
      

      只要你不介意所说的一致性。

      【讨论】:

        猜你喜欢
        • 2015-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-24
        • 2022-06-14
        • 2019-07-23
        相关资源
        最近更新 更多