Description
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.