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
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));