Skip to content

as const, but for JavaScriptΒ #42884

Closed
Closed

Description

@AlCalzone

Suggestion

πŸ” Search Terms

as const javascript

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Several of newer useful TypeScript features are of limited use when writing JavaScript. As an example, the workaround for the recently re-opened #41631 is to use as const, which is not available in JS. Therefore I suggest to add the as const assertion to JS. For this purpose, the @type JSDoc could be reused:

const id1 = `my-tree.0.${someString}`; // inferred as string
/** @type {const} */
const id1 = `my-tree.0.${someString}`; // type: `my-tree.0.${string}`

πŸ“ƒ Motivating Example

See #41631

πŸ’» Use Cases

In iobroker, objects in the database have different types that can be distinguished by how the ID is shaped. The different object types take different properties, so type-checking this would go a long way to reduce errors.

The type declarations already reflect this:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/81e930ed9983d081271ebf1978551b1e4c8b5b16/types/iobroker/iobroker-tests.ts#L649-L707
but this feature is limited to TypeScript devs who can use as const.

While these tests are hard-coded for string literals, in the real world most of our developers use JS and IDs are often built on the fly, e.g.

const id = `my-tree.0.${someString}`; // inferred as string
setObject(id, { /* I could really use a better type for this object */ });

If id was instead typed as my-tree.0.${string}, the object type in setObject could be more specific to the purpose it actually serves.

Activity

  1. jcalz commented on Feb 19, 2021

    @jcalz
    Contributor
  2. AlCalzone commented on Feb 19, 2021

    @AlCalzone
    ContributorAuthor

    Damn, my search must not be working :(

  3. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions