Some examples of how to do TypeScript with only jsdoc comments.
Note: the extra parenthesis are necessary here.
// TypeScript
const body = response.body as any
// JavaScript + jsdoc
const body = /** @type {any} */ (response.body)
Adding types to function arguments (name
and options
):
// TypeScript
function greet(name: string): void {
console.log(name)
}
// JavaScript + jsdoc
/**
* @param {string} name
* @returns {void}
*/
function greet(name) {
console.log(name)
}
Importing types from another file like users.ts
:
// TypeScript
import { User } from './users'
// JavaScript + jsdoc
/** @typedef {import('./users').User} User */
// TypeScript
let page: { title: string, url: string };
// JavaScript + jsdoc
/** @type {{ title: string, url: string }} */
let page;
// TypeScript (via type literals)
type Page = { title: string, url: string }
// TypeScript (via interface)
interface Page { title: string, url: string }
// JavaScript + jsdoc
/**
* @typedef {Object} Page
* @property {string} title
* @property {string} url
*/
// JavaScript + jsdoc (via inline TypeScript)
/** @typedef {{ title: string, url: string }} Page */
// TypeScript
function square<T>(input: T): T { return input * input; }
// JavaScript + jsdocc
/**
* @template T
* @param {T} input
* @returns {T}
*/
function square(input) { return input * input; }
class Dog {
name: string
constructor(name: string) { … }
}
// JavaScript + jsdoc
class Dog {
/** @type {string} */
this.name;
/**
* @param {string} name
*/
constructor(name) { … }
}
/* TypeScript */
const btn = document.querySelector('#ok') as HTMLButtonElement
/* JavaScript + jsdoc */
const btn = /** @type {HTMLButtonElement} */ (document.querySelector('#ok'))