Recipes

Recipes for typing real JavaScript

Each recipe starts from a concrete question about real code, answers it up front, then shows the TypeScript spelling of the same thing and the mistakes tsc catches. Every example on a recipe page is a real file checked with tsc when the site is built.

The recipes are listed in six groups: functions, objects and data, classes, modules and packages, Node.js and the browser, and frameworks and tests.

Functions

Parameters that are optional, rest or callbacks, overloads and generic helpers, this, and what async functions and generators return.

Objects and data

Options objects, config objects, keys and records, enums without enum, unions you narrow, guards and assertions, maps, sets and tuples.

Classes

Fields and constructors, private members, accessors, static members, subclasses, mixins and interfaces a class promises to implement.

Modules and packages

Exports in CommonJS and ES modules, sharing types between files, dynamic imports, packages without types, globals, environment variables and JSON files.

Node and platforms

Node.js callbacks, events, streams, child processes, command-line options, timers and buffers; the DOM, fetch, storage, custom elements and sockets.

Frameworks and tests

Express handlers and middleware, React and Svelte components written in JavaScript, test files, and publishing a package with types.