Skip to content

JSDoc Type cast to const does not work in variable-like initializers #45463

@rbuckton

Description

@rbuckton

Bug Report

🔎 Search Terms

jsdoc cast as const

🕗 Version & Regression Information

  • We have half-supported as const in JSDoc since it was added to TypeScript (~v3.5)

⏯ Playground Link

Playground link with relevant code

💻 Code

// @checkJs: true
// @allowJs: true
// @strict: true

let x = /** @type {const} */(1); // error: cannot find name 'const'
x; // any

let y;
y = /** @type {const} */(1); // works
y; // 1

let z = (/** @type {const} */(1)); works
z; // 1

🙁 Actual behavior

In a JavaScript file, using a /** @type {const} */( expr ) cast in the initializer of any variable-like declaration reports a "Cannot find name 'const'" error:

  • VariableDeclaration
  • PropertyDeclaration
  • PropertyAssignment
  • BindingElement
  • ParameterDeclaration

In any other position, the cast correctly behaves like a TypeScript as const assertion.

🙂 Expected behavior

In a JavaScript file, using a /** @type {const} */( expr ) cast should behave like TypeScript's as const in any position, not just random arguments.

Workaround:

While let x = /** @type {const} */({a: 1}) does not work, let x = (/** @type {const} */({a: 1})) does. This is because our logic to get the effective type annotation node for a variable-like declaration treats the type cast in the initializer as part of the declaration.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions