31

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.

Adam Coster
  • 1,162
  • 1
  • 9
  • 16
  • 1
    I doubt it would exist. `as const` is a TS directive that allows you to use runtime code as compile time type. However, JSDoc is entirely separate from code and especially disassociated with runtime code. It allows you to annotate some things but it certainly doesn't have the entire flexibility of TS. – VLAZ Oct 27 '20 at 17:19
  • 2
    JSDoc type assertions are explained in the handbook https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#casts So my guess would have been `/** @type {const} */ (1)` but it does not work. – Titian Cernicova-Dragomir Oct 27 '20 at 17:58

1 Answers1

56

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.

ZachB
  • 13,051
  • 4
  • 61
  • 89
  • the note on parentheses was very helpful! your note says this was since v4.5, however I believe [you may be referring to v2.5](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-5.html#type-assertioncast-syntax-in-checkjsts-check-mode)? and [shown in the handbook here](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#casts) I also can confirm this works with tuples ```const test = /** @type {const} */ (["hello",42]); // [string,number]``` – bristweb Aug 29 '23 at 14:25