Skip to Content
  • Website
Codsen
  • Home
  • Open Source
  • Articles
  • About

prevOpen Source→tsd-extractnext

tsd-extract0.10.1

Extract any definition from TS definitions file string

Downloads per monthChangelogMIT Licenselibera manifesto
  • the top
  • Installation
  • Quick Take
  • Examples
  • IDEA
  • API — EXTRACT()
  • IDENTIFIERS
  • CONTENT
  • VALUE
  • API — JOIN()
  • API — ROYSSORT()
  • API — DEFAULTS
  • API — VERSION
  • API — TYPES
  • Changelog

Installation

Quick Take

Examples

  • Extract a nested member
  • Extracting function type definitions
  • Join two object types into one
  • List all declarations in the source
  • Report a declaration that was not found
  • Omit the trailing semicolon
  • Require a statement to contain a string
  • Sorting exports
  • Strip the as aliases from an export

Idea

Take a .d.ts TypeScript definitions file as string, extract any definition from it.

No parsing, no dependencies, it’s only ~4.5KB minified.

This program is also suitable for using in MDX where all dependencies are bundled. You would not bundle the whole TypeScript in your blog post strings, would you?

Theoretically, you can use TypeScript and its parser directly, traverse the AST and do the same what this program does, just slower and more cumbersome.

API — extract()

The main function extract() is imported like this:

It’s a function which takes two input arguments:

Input argumentTypeObligatoryDescription
input
Type: String
Obligatory: yes
inputStringyesType definitions source as string.
def
Type: String
Obligatory: yes
defStringyesName of a definition to extract. Can be system keyword (export) or a any variable’s name.
opts
Type: Plain object
Obligatory: no
optsPlain objectnoOptional Options Object.

The Optional Options Object has the following shape:

KeyTypeDefaultDescription
extractAll
Type: boolean
Default: false
extractAllbooleanfalseIf enabled, the program will also extract an array of all unique definitions found. This is for GUI app.
semi
Type: boolean
Default: true
semibooleantrueIf set to false, any semicolons will be omitted from extracted string values and not reported in string index locations. As if they didn’t exist in the source.
mustInclude
Type: string
Default: "" (empty string)
mustIncludestring"" (empty string)Force algorithm to look for an extra def to be present in the finding. Used when there are multiple findings and program otherwise returns the wrong-one.
stripAs
Type: boolean
Default: false
stripAsbooleanfalseIf enabled, instead of export { x as y } from "z"; it will produce export { y } from "z";
contentSort
Type: function
Default: undefined
contentSortfunctionundefinedOptionally, to sort export contents, pass a custom compare functionopens in a new tab to Array.prototype.sort() used under the hood, see examples

Here are all defaults in one place for copying:

This function will return a plain object of a shape:

You’ll see three terms used:

  • “identifiers”
  • “content”
  • “value”

Identifiers

That’s any “word” which is located up to equal sign, or bracket of any kind:

// three indentifiers here:
declare function a<b>(c: d): e;
// ^^^^ ^^^^^^^^ ^
//  1      2     3
// two identifiers here:
interface Opts {
  // ^^^^ ^^^^
  //  1     2
  whitelist: string[];
  backend: HeadsAndTailsObj[];
}
// one identifier here:
export { x } from "y";
// ^^^
//  1

The definition def you pass will be matched against these extracted identifiers.

Content

That’s everything after identifiers but excluding any generics and variables in brackets:

// three indentifiers here:
declare function a<b>(c: d): e;
//                   ^^^^^^^^^^
//                   all this^
//
// ^ semicolon will be excluded (if present) opts.semi === false

Value

That’s the whole found statement, from the very first character to the very last-one (except the semicolon if opts.semi === false).

API — join()

This function extracts and merges the contents of multiple interfaces:

import { strict as assert } from "assert";
import { join } from "tsd-extract";
let source1 = `type x = {
    a: string;
  } & {
    b: number;
  }`;
let source2 = ` = Statement & {
      c: boolean;
    } & {
      d: null | string;
    }`;
let source3 = ` = zz & {
      e: number;
    } & {
      f: (g) => void;
    }`;
let source4 = null;
let source5 = "";
assert.equal(
  join(source1, source2, source3, source4, source5),
  `{
  a: string;
  b: number;
  c: boolean;
  d: null | string;
  e: number;
  f: (g) => void;
}`,
);

The main function join() is imported like this:

It’s a function which takes any amount of string input arguments:

The function will return a string — all contents between curly braces extracted, and each line’s indentation set to two spaces.

API — roysSort()

The function roysSort() is imported like this:

A ready-made compare functionopens in a new tab to pass as opts.contentSort. It sorts an export {...} statement’s contents into the order Codsen packages use:

  1. Lowercase-initial names (the functions) come first, alphabetically.
  2. Then defaults, then version.
  3. Then uppercase-initial names (the types), alphabetically.
import { extract, roysSort } from "tsd-extract";

console.log(["version", "Opts", "defaults", "extract", "Res", "join"].sort(roysSort));
// => ["extract", "join", "defaults", "version", "Opts", "Res"]

Pass it to extract() to normalise a whole export statement:

import { extract, roysSort } from "tsd-extract";

const source = `export { defaults, extract, join, roysSort, version };`;

console.log(extract(source, "export", { contentSort: roysSort }).content);
// => "{ extract, join, roysSort, defaults, version };"

That’s how this website renders the export lists you see on these pages.

API — defaults

You can import defaults:

It's a plain object:

The main function calculates the options to be used by merging the options you passed with these defaults.

API — version

You can import version:

API — types

This package is written in TypeScript and exports the following types:

TypeDescription
Opts
Type: Opts
OptsThe Optional Options Object of extract(), documented above.
Statement
Type: Statement
StatementOne extracted definition — its identifiers, content and value, plus the index of where each starts and ends.
ReturnType
Type: ReturnType
ReturnTypeWhat extract() returns: a Statement plus all (present when opts.extractAll is on) and error.
Chunk
Type: Chunk
ChunkAn intermediate piece the algorithm records while scanning: startsAt, endsAt and the identifiers found in it.
import type { Chunk, Opts, ReturnType, Statement } from "tsd-extract";

Changelog

Open Changelog
↑ back to top
prev next

Copyright

All rights reserved © Roy Revelt 2026
All our open source packages are under MIT licenceopens in a new tab

Activities

🐛 See a bug? Raise an issueopens in a new tab
💘 Check out the Indiewebopens in a new tab and Libera manifestoopens in a new tab