Typing an untyped library
A partner signs the webhooks Relay receives with a small JavaScript library, legacy-sig.js, that they hand out
as a file. It has no types and no npm package. Relay imports it, and with strict on, tsc stops at the first
import: Could not find a declaration file for module './legacy-sig.js'. The file “implicitly has an any type”.
You have three ways forward, from worst to best: silence the error, declare the module as any, or write its
declaration file. Only the last one catches a bug when someone calls sign(42, "body").
What the error means
Section titled “What the error means”TypeScript does not read .js files here (the course config has no allowJs). For an import of ./legacy-sig.js
it looks next to the file for legacy-sig.ts and then legacy-sig.d.ts. A .d.ts is a file with only
declarations: types, no code. Find one and the import is typed by it. Find nothing and, under noImplicitAny
(part of strict), the import is an error.
Because the .d.ts sits next to the .js and has the same base name, it is found without any setting. The
specifier stays ./legacy-sig.js, and Bun runs the real JavaScript file.
Read the JavaScript first
Section titled “Read the JavaScript first”A declaration file describes what the code does, so read the code. The part of legacy-sig.js that matters is
what it returns, what it accepts, and how its arguments change meaning:
import { createHmac, timingSafeEqual } from "node:crypto"
export const VERSION = "2.3.1"
export function sign(secret, body, options) { const opts = options || {} const algorithm = opts.algorithm || "sha256" const encoding = opts.encoding || "hex" const digest = createHmac(algorithm, secret).update(body).digest(encoding) return opts.prefix === false ? digest : algorithm + "=" + digest}
export function verify(secret, body, signature, options, callback) { if (typeof options === "function") { callback = options options = undefined } const algorithm = (options && options.algorithm) || signature.split("=")[0] let ok try { const expected = Buffer.from(sign(secret, body, { ...options, algorithm })) const actual = Buffer.from(signature) ok = expected.length === actual.length && timingSafeEqual(expected, actual) } catch (error) { if (callback) return void callback(error, false) throw error } if (callback) return void callback(null, ok) return ok}
export function parseHeader(header) { const parts = Object.fromEntries(header.split(",").map((p) => p.split("="))) if (!parts.t || !parts.v1) return null return { timestamp: Number(parts.t), signature: parts.v1 }}Three things to extract:
sign(secret, body, options)takes an optional options bag and always returns a string.verifyhas three call shapes. Without a callback it returns a boolean. With one, it returns nothing and callscallback(error, ok). Theoptionsargument can be skipped.parseHeaderreturns an object ornull.
Options bags and literal unions
Section titled “Options bags and literal unions”An options bag becomes an interface with optional properties. When the JavaScript checks a string against known
values, use a union of literals, not string:
export type Algorithm = "sha256" | "sha1"export type Encoding = "hex" | "base64"
export interface SignOptions { algorithm?: Algorithm encoding?: Encoding prefix?: boolean}
export declare function sign(secret: string, body: string, options?: SignOptions): string
export const ok: string = sign("whsec", "{}", { algorithm: "sha1" })// @ts-expect-error: "md5" is not an algorithm the library knowsexport const bad: string = sign("whsec", "{}", { algorithm: "md5" })declare function here is declare from lesson 1: a signature with no body. In a .d.ts file every top-level
export function is already ambient, so the keyword is optional there, but in a .ts file you need it.
The bug this prevents: algorithm: "md5" reaches the library, which throws at runtime from inside createHmac.
Overloads for call shapes
Section titled “Overloads for call shapes”verify takes a different number of arguments and returns a different type in each shape. One signature with
optional parameters can’t say “no callback means boolean, a callback means void”. Overloads can: several signatures
and no body.
type VerifyCallback = (error: Error | null, ok: boolean) => void
export declare function verify(secret: string, body: string, signature: string): booleanexport declare function verify(secret: string, body: string, signature: string, callback: VerifyCallback): voidexport declare function verify( secret: string, body: string, signature: string, options: { algorithm?: "sha256" | "sha1" }, callback: VerifyCallback): void
export const sync: boolean = verify("s", "b", "sha256=ab")verify("s", "b", "sha256=ab", (error, ok) => { // `error` is Error | null and `ok` is boolean, with no annotations written here console.log(error?.message, ok)})// @ts-expect-error: options without a callback is not a shape the library supportsverify("s", "b", "sha256=ab", { algorithm: "sha1" })TypeScript tries the overloads from top to bottom and uses the first that fits. Put the most specific one first. The callback’s parameters get their types from the overload, so a caller doesn’t annotate them. A shape that has no overload is an error, which is exactly what you want when the JavaScript only handles three.
ES exports and export =
Section titled “ES exports and export =”Match the declaration to how the JavaScript exports. legacy-sig.js uses ES export statements, so the .d.ts
uses export too. Old CommonJS libraries that set module.exports = fn are typed with export = fn, and importing
them can need esModuleInterop to import. New code in this course is ESM only, so write named exports and skip export =.
The declaration is a promise, and a wrong one passes tsc. If you write export default function sign() in the
.d.ts but the JavaScript only has the named export, this compiles and Bun fails on import with
SyntaxError: Missing 'default' export in module. Test the declaration against the real file, as the exercise does.
Wildcard modules
Section titled “Wildcard modules”Not every import is JavaScript. Bun can import a .sql file as text with an import attribute, and tsc has never
heard of .sql. A wildcard module declares a type for every specifier that matches the pattern:
declare module "*.sql" { const text: string export default text}import insertJob from "./insert-job.sql" with { type: "text" }
export const statement: string = insertJob.trim()The same trick types images (declare module "*.png") and anything else a bundler turns into a value. As in
lesson 1, the file must be a script. A wildcard inside a module is an error: Invalid module name in augmentation.
The shorthand, and why it gives you any
Section titled “The shorthand, and why it gives you any”The fastest way to quiet Could not find a declaration file is a shorthand declaration with no body:
declare module "legacy-pkg"Every import from legacy-pkg now compiles, and every imported name is any: sign(1, 2, 3), legacy.whatever.you.like,
all accepted. It is useful as a first step while you migrate. It is not a type, and any is contagious: a value
that came from an any call can flow into Relay’s typed functions without a check. The shorthand also
only works for a bare package name. It can’t name a relative path such as ./legacy-sig.js, for that you write the file
next to it, as in the exercise.
Exercise
Section titled “Exercise”Copy these files into the Relay project in one folder, such as src/declarations/untyped-js/. Add legacy-sig.js
and insert-job.sql too (they are the vendored library and the query). Rename each x.starter.y file to x.y:
legacy-sig.starter.d.ts, sql.starter.d.ts and main.starter.ts.
Write legacy-sig.d.ts and sql.d.ts so that main.ts and misuse.ts type-check and the lines in misuse.ts
stay errors. Run bun test in that folder. The tests also run the real JavaScript through your types.
// legacy-sig.js is vendored JavaScript (read it first). This file is its first, lazy typing:// every name exists and is `any`, so nothing is checked. Replace it with real types.//// Rules:// - VERSION is a string.// - sign(secret, body, options?) returns a string. options is an object with optional// algorithm ("sha256" | "sha1"), encoding ("hex" | "base64") and prefix (boolean).// - verify has three call shapes, as three overloads:// verify(secret, body, signature): boolean// verify(secret, body, signature, callback): void// verify(secret, body, signature, options, callback): void// The callback receives (error: Error | null, ok: boolean). Only `algorithm` is allowed in// verify's options.// - parseHeader(header) returns { timestamp: number; signature: string } or null.// - Keep ES module syntax: named exports, no `export =`.
export const VERSION: anyexport const sign: anyexport const verify: anyexport const parseHeader: any// main.ts imports "./insert-job.sql". Teach the compiler that every "*.sql" import is a text file:// the default export is a string.import { parseHeader, sign, verify } from "./legacy-sig.js"import insertJob from "./insert-job.sql" with { type: "text" }
export interface Delivery { readonly header: string readonly body: string}
export function signBody(secret: string, body: string): string { return sign(secret, body, { algorithm: "sha256", encoding: "base64", prefix: false })}
export function isAuthentic(secret: string, delivery: Delivery): boolean { const parsed = parseHeader(delivery.header) if (parsed === null) return false return verify(secret, delivery.body, `sha256=${parsed.signature}`)}
export function verifyAsync(secret: string, body: string, signature: string): Promise<boolean> { return new Promise((resolve, reject) => { verify(secret, body, signature, (error, ok) => (error === null ? resolve(ok) : reject(error))) })}
export const insertStatement: string = insertJob.trim()import { parseHeader, sign, verify, VERSION } from "./legacy-sig.js"
// @ts-expect-error: the secret is a string, not a numbersign(42, "body")
// @ts-expect-error: "md5" is not an algorithm legacy-sig supportssign("secret", "body", { algorithm: "md5" })
// @ts-expect-error: sign returns a string, not a Bufferexport const buffer: Buffer = sign("secret", "body")
// @ts-expect-error: the callback receives (error, ok), so `ok` is a boolean, not a stringverify("secret", "body", "sig", (_error, ok: string) => {})
// @ts-expect-error: verify without a callback returns a boolean, not voidexport const nothing: void = verify("secret", "body", "sig")
// @ts-expect-error: verify has no four-argument form with an options objectverify("secret", "body", "sig", { algorithm: "sha1" })
// @ts-expect-error: parseHeader can return null, so .timestamp needs a check firstexport const t: number = parseHeader("t=1,v1=a").timestamp
// @ts-expect-error: VERSION is a stringexport const major: number = VERSIONimport { expect, test } from "bun:test"import { createHmac } from "node:crypto"import { existsSync } from "node:fs"import { join } from "node:path"import { insertStatement, isAuthentic, signBody, verifyAsync } from "./main.ts"
const tsc = [join(import.meta.dir, "../../../node_modules/.bin/tsc"), join(process.cwd(), "node_modules/.bin/tsc")].find(existsSync) ?? "tsc"
function check(files: string[]): { code: number; out: string } { const r = Bun.spawnSync( [tsc, "--noEmit", "--strict", "--target", "esnext", "--module", "esnext", "--moduleResolution", "bundler", "--verbatimModuleSyntax", "--allowImportingTsExtensions", "--skipLibCheck", "--ignoreConfig", "--types", "bun", ...files], { cwd: import.meta.dir } ) return { code: r.exitCode, out: r.stdout.toString() + r.stderr.toString() }}
const secret = "whsec_test"const body = '{"id":"job_1"}'const hex = createHmac("sha256", secret).update(body).digest("hex")
test("the declarations make main.ts and misuse.ts type-check", () => { const r = check(["legacy-sig.d.ts", "sql.d.ts", "main.ts", "misuse.ts"]) expect(r.out).toBe("") expect(r.code).toBe(0)})
test("signBody uses the options bag", () => { expect(signBody(secret, body)).toBe(createHmac("sha256", secret).update(body).digest("base64"))})
test("isAuthentic accepts a good header and rejects a bad one", () => { expect(isAuthentic(secret, { header: `t=1700000000,v1=${hex}`, body })).toBe(true) expect(isAuthentic(secret, { header: `t=1700000000,v1=sha256=${hex.replace(/.$/, "0")}`, body })).toBe(false) expect(isAuthentic(secret, { header: "garbage", body })).toBe(false)})
test("verifyAsync wraps the callback form", async () => { expect(await verifyAsync(secret, body, `sha256=${hex}`)).toBe(true) expect(await verifyAsync(secret, body, `sha256=${"0".repeat(64)}`)).toBe(false)})
test("the .sql import is the file's text", () => { expect(insertStatement).toBe("INSERT INTO jobs (id, kind, payload) VALUES ($id, $kind, $payload)")})The starter types every export as any, the shorthand’s behavior, so misuse.ts reports a list of
unused @ts-expect-error lines, and main.ts can’t infer the callback’s parameters. Each real type you add removes some of them.
- No
.d.tsnext to a.jsimport is an error understrict. Alegacy-sig.d.tsnext tolegacy-sig.jsis found automatically. - Read the JavaScript, then describe it: options bags are interfaces, known strings are literal unions.
- Overloads describe call shapes. The first matching signature wins, so order them specific first.
- Match the JavaScript’s exports. A wrong declaration passes
tscand fails at runtime, so test against the real file. declare module "*.sql"types a non-code import, and it must be in a script file.declare module "pkg"makes everythingany. Treat it as a stopgap.
Further reading
Section titled “Further reading”- TypeScript handbook: Modules reference, ambient modules: wildcard and shorthand module declarations.
- TypeScript handbook: Modules reference, export =: typing CommonJS-style exports.
- TypeScript handbook: Declaration Files, by example: overloaded function declarations.