Skip to content

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").

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.

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:

legacy-sig.js
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:

  1. sign(secret, body, options) takes an optional options bag and always returns a string.
  2. verify has three call shapes. Without a callback it returns a boolean. With one, it returns nothing and calls callback(error, ok). The options argument can be skipped.
  3. parseHeader returns an object or null.

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 knows
export 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.

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): boolean
export declare function verify(secret: string, body: string, signature: string, callback: VerifyCallback): void
export 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 supports
verify("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.

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.

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:

sql.d.ts (a script, so the declaration is global)
declare module "*.sql" {
const text: string
export default text
}
main.ts
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 fastest way to quiet Could not find a declaration file is a shorthand declaration with no body:

shorthand.d.ts
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.

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.d.ts
// 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: any
export const sign: any
export const verify: any
export const parseHeader: any
sql.d.ts
// main.ts imports "./insert-job.sql". Teach the compiler that every "*.sql" import is a text file:
// the default export is a string.
main.ts
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()
misuse.ts
import { parseHeader, sign, verify, VERSION } from "./legacy-sig.js"
// @ts-expect-error: the secret is a string, not a number
sign(42, "body")
// @ts-expect-error: "md5" is not an algorithm legacy-sig supports
sign("secret", "body", { algorithm: "md5" })
// @ts-expect-error: sign returns a string, not a Buffer
export const buffer: Buffer = sign("secret", "body")
// @ts-expect-error: the callback receives (error, ok), so `ok` is a boolean, not a string
verify("secret", "body", "sig", (_error, ok: string) => {})
// @ts-expect-error: verify without a callback returns a boolean, not void
export const nothing: void = verify("secret", "body", "sig")
// @ts-expect-error: verify has no four-argument form with an options object
verify("secret", "body", "sig", { algorithm: "sha1" })
// @ts-expect-error: parseHeader can return null, so .timestamp needs a check first
export const t: number = parseHeader("t=1,v1=a").timestamp
// @ts-expect-error: VERSION is a string
export const major: number = VERSION
main.test.ts
import { 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.ts next to a .js import is an error under strict. A legacy-sig.d.ts next to legacy-sig.js is 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 tsc and 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 everything any. Treat it as a stopgap.