Appendix D. Recipes for Writing Declaration Files for Third-Party JavaScript Modules

This appendix covers a few key building blocks and patterns that come up over and over again when typing third-party modules. For a deeper discussion of typing third-party code, head over to “JavaScript That Doesn’t Have Type Declarations on DefinitelyTyped”.

Since module declaration files have to live in .d.ts files and so can’t contain values, when you declare module types you need to use the declare keyword to affirm that values of the given type really are exported by your module. Table D-1 provides a short summary of regular declarations and their type declaration equivalents.

Table D-1. TypeScript and its type-only equivalents
.ts .d.ts

var a = 1

declare var a: number

let a = 1

declare let a: number

const a = 1

declare const a: 1

function a(b) { return b.toFixed() }

declare function a(b: number): string

class A { b() { return 3 } }

declare class A { b(): number }

namespace A {}

declare namespace A {}

type A = number

type A = number

interface A { b?: string }

interface A { b?: string }

Types of Exports

Whether your module uses global, ES2015, or CommonJS exports will affect how you write your declaration files.

Globals

If your module only assigns values to the global namespace and doesn’t actually export anything, you can just create a script-mode file (see “Module Mode Versus Script Mode”) and prefix your variable, function, and class declarations with declare

Get Programming TypeScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.