Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Last active November 19, 2022 23:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rstacruz/519ef0d85666cbd8057942177567af07 to your computer and use it in GitHub Desktop.
Save rstacruz/519ef0d85666cbd8057942177567af07 to your computer and use it in GitHub Desktop.

TypeScript jsdoc examples

Some examples of how to do TypeScript with only jsdoc comments.

Type casting

Note: the extra parenthesis are necessary here.

// TypeScript
const body = response.body as any

// JavaScript + jsdoc
const body = /** @type {any} */ (response.body)

Function argument

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

Importing types from another file like users.ts:

// TypeScript
import { User } from './users'

// JavaScript + jsdoc
/** @typedef {import('./users').User} User */

Inline variable types

// TypeScript
let page: { title: string, url: string };

// JavaScript + jsdoc
/** @type {{ title: string, url: string }} */
let page;

Complex types

// 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 */

Templates

// 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; } 

Classes

class Dog {
  name: string
  constructor(name: string) {  }
}

// JavaScript + jsdoc
class Dog {
  /** @type {string} */
  this.name;
  
  /**
   * @param {string} name
   */
   constructor(name) {  }
}

More examples

/* TypeScript */
const btn = document.querySelector('#ok') as HTMLButtonElement

/* JavaScript + jsdoc */
const btn = /** @type {HTMLButtonElement} */ (document.querySelector('#ok'))

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment