'JSDoc equivalent to Typescript's `as const`?
I'm in an old project that is too huge to easily convert to Typescript, so I've been using JSDoc instead. The Typescript feature that I can't figure out how to replicate in JSDoc is using as const
to fully type the property names and values of a static object.
// In Typescript
const anObject = {hello: 'world'} as const;
// (type shows as {hello:'world'} instead of {hello:string}
Is there any equivalent for this in JSDoc? I've been completely unable to find anything that does this (@readonly
and @const
don't do it), so instead I have to basically copy-paste any static object as a type to be able to properly type these cases, which certainly isn't DRY.
Solution 1:[1]
Since Typescript 4.5:
const foo = /** @type {const} */ ({x: 1});
const bar = /** @type {const} */ ("baz");
Note that the parentheses are required; this is cast syntax, not normal type annotation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |