Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast TypeScript type in javascript using JSDoc

When using TypeScript to check JavaScript code, how do you cast to a different type than is inferred? Typescript has the <Type> and as Type syntax but these aren't valid in JavaScript.

/**
 * @param {{id: string, value: number}} details - object with required properties
 */
function stringifyObject(details) {
  return `${details.id}: ${details.value}`;
}

const testValue = {id: 'no-value'};
stringifyObject(testValue); // want to cast testValue to ignore missing property
stringifyObject(/** @type {any} */ testValue); // this doesn't work
like image 617
Chic Avatar asked Aug 31 '25 01:08

Chic


1 Answers

The /** @type */ comment is close. According to the TypeScript Handbook it just needs parenthesis around the value being cast.

TypeScript borrows cast syntax from Google Closure. This lets you cast types to other types by adding a @type tag before any parenthesized expression.

So in the original example you would write the following:

// Wrap value being cast in parenthesis 
stringifyObject(/** @type {any} */ (testValue));
like image 179
Chic Avatar answered Sep 02 '25 15:09

Chic