You can leverage TypeScript's powerful type engine inside standard JavaScript (.js) files without a full compilation build step by using // @ts-check and JSDoc annotations.
// @ts-check: Top-of-file directive enabling TypeScript type checking in .js files.@param {type} name: Defines parameter types.@returns {type}: Defines function return type.@type {type}: Annotates variable or property type.@typedef: Defines custom object type contracts in JSDoc.src/utils.js)// @ts-check
/**
* @typedef {Object} DatabaseConfig
* @property {string} host
* @property {number} port
* @property {boolean} [ssl] Optional SSL flag
*/
/**
* Connects to database cluster.
* @param {DatabaseConfig} config
* @returns {string} Status message
*/
function connectCluster(config) {
const sslStatus = config.ssl ? "SSL Enabled" : "SSL Disabled";
return `Connected to ${config.host}:${config.port} [${sslStatus}]`;
}
// Valid Call
console.log(connectCluster({ host: "localhost", port: 5432, ssl: true }));
// Invalid Call (Triggering VS Code TypeScript error in JS file!)
// connectCluster({ host: "localhost", port: "5432" }); // Error: Type 'string' is not assignable to type 'number'
// @ts-check allows legacy JavaScript codebases to adopt type checking incrementally without changing file extensions immediately.checkJs in tsconfig.json: Enable "checkJs": true to apply type checking across all project .js files automatically.@param {import('./types').User} user.What comment line must be placed at the very top of a JavaScript file to enable TypeScript type checking? (Answer: // @ts-check)
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With