Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

as const, but for JavaScript #42884

Closed
5 tasks done
AlCalzone opened this issue Feb 19, 2021 · 2 comments
Closed
5 tasks done

as const, but for JavaScript #42884

AlCalzone opened this issue Feb 19, 2021 · 2 comments

Comments

@AlCalzone
Copy link
Contributor

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.

@jcalz
Copy link
Contributor

jcalz commented Feb 19, 2021

#30445 ?

@AlCalzone
Copy link
Contributor Author

Damn, my search must not be working :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants