What is the “as syntax” pointed out by tslint?

前端 未结 2 1316
故里飘歌
故里飘歌 2020-12-03 13:33

I upgraded tslint and now it complains about:

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


        
相关标签:
2条回答
  • 2020-12-03 14:02

    Refactor your code like this:

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

    As pointed out in the TypeScript Deep Dive book by Basarat Ali Syed, it says about type casting:

    as foo vs. <foo>

    Originally the syntax that was added was <foo>. This is demonstrated below:

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

    However there is an ambiguity in the language grammar when using

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

    Therefore it is now recommended that you just use as foo for consistency.

    Type Assertion vs. Casting

    The reason why it's not called "type casting" is that casting generally implies some sort of runtime support. However type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.

    0 讨论(0)
  • 2020-12-03 14:09

    If you want to suppress the error, you can as well go to tslint.json and include

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

    provided you don't mind consistence as said.

    0 讨论(0)
提交回复
热议问题