javascriptcastingvisual-studio-codejsdoclanguageservice

JSDoc/JavaScript Language Service: how to annotate an expression? (how to cast)


I'm using Visual Studio Code with JavaScript Language Service configured as:

{
    "compilerOptions": {
        "checkJs": true
    }
}

And I can't find a way to cast something, like here:

Error message

The example above should work in Closure Compiler (unverified), as documented here. But I can't find the equivalent syntax for JavaScript Language Service.

I also tried with the following simpler statement, which does not work either:

let castedWindow = (/** @type {any} */(window));  // castedWindow: Window (I want `any`)

I'm asking how to do casts, and if someone happens to know where the syntax is documented (or, if undocumented, just how it works).

Is what I'm asking even possible?

Thanks for your time!


Solution

  • As of TypeScript 2.5, support for type assertion/cast syntax in checkJs/@ts-check mode has been introduced.

    Type assertion/cast syntax in checkJs/@ts-check mode

    TypeScript 2.5 introduces the ability to assert the type of expressions when using plain JavaScript in your projects. The syntax is an /** @type {...} */ annotation comment followed by a parenthesized expression whose type needs to be re-evaluated. For example:

    var x = /** @type {SomeType} */ (AnyParenthesizedExpression);