Skip to content
jshacks.dev
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read
Summarize in AI

Importing a package that ships no types fails under strict: Could not find a declaration file for module. You can write the part you use in a file next to your code.

types/legacy-slugify.d.tsTypeScript
declare module 'legacy-slugify' {
  export default function slugify(text: string, options?: { lower?: boolean }): string;
}
main.tsTypeScript
import slugify from 'legacy-slugify';

console.log(slugify('Hello World', { lower: true }));
Text
hello-world

A declare module 'name' block with a body describes the module's exports. The compiler now checks the arguments and knows the return type, and a call such as slugify(42) is an error. Keep the file in a folder covered by include in tsconfig.json, and give it no top-level import or export, or it stops being an ambient declaration. See modules .d.ts.

The shorthand declare module 'legacy-slugify'; with no body types everything from the module as any, which silences the error and checks nothing. Use it as a first step and replace it as you rely on more of the API. Check DefinitelyTyped first: an @types/ package may already exist.

Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Type Node.js streams

Type a Node.js Transform stream and pipe it with the promise version of pipeline so chunk types and errors are checked. Needs @types/node 22 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.