Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 272
bscotchAdam Avatar asked Oct 27 '20 17:10

bscotchAdam


People also ask

Does JSDoc work with TypeScript?

You can use most JSDoc type syntax and any TypeScript syntax, from the most basic like string to the most advanced, like conditional types.

What is Typedef in JS?

The @typedef tag is useful for documenting custom types, particularly if you wish to refer to them repeatedly. These types can then be used within other tags expecting a type, such as @type or @param. Use the @callback tag to document the type of callback functions.

Is JSDoc useful?

JSDoc 3 is an API documentation generator for JavaScript, similar to Javadoc or phpDocumentor. You add documentation comments directly to your source code, right alongside the code itself. I use JSDoc more than 4 years and found it extremely good and useful. Documentation is important to have in a project.


Video Answer


1 Answers

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.

like image 121
ZachB Avatar answered Sep 19 '22 07:09

ZachB