Skip to content
jshacks.dev
TypeScript

Export types next to the functions that use them

Export the option and result types from the same module as the function that uses them, so callers import both in one statement. Works in TypeScript 5.

1 min read
Summarize in AI

A function whose parameter type is only reachable through Parameters<typeof fn> makes every caller work harder. Export the types beside it.

parse.tsTypeScript
export interface ParseOptions {
  radix?: number;
}

export type ParseResult = { ok: true; value: number } | { ok: false };

export function parseInteger(input: string, options: ParseOptions = {}): ParseResult {
  const value = Number.parseInt(input, options.radix ?? 10);
  return Number.isNaN(value) ? { ok: false } : { ok: true, value };
}
main.tsTypeScript
import { parseInteger, type ParseOptions } from './parse.js';

const hex: ParseOptions = { radix: 16 };
console.log(parseInteger('ff', hex), parseInteger('zz'));
Text
{ ok: true, value: 255 } { ok: false }

The import brings the function and its option type in one line, with the inline type modifier marking what is erased. Because both live in parse.ts, a change to ParseOptions is made in the same file as the code that reads it, and the compiler checks every caller. The inline modifier is covered in the TypeScript 4.5 notes.

Export only what callers need to name. A type used only inside the function body stays private, and a public type that mentions a private one fails the build with an error about the exported declaration, which is a hint to export it too.

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

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

Get new posts by email

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

Unsubscribe in one click. No spam, ever.