typestar

Type-only imports in TypeScript

Importing a type without importing a value, so the import can vanish.

import type { Readable } from "node:stream";
import { createReadStream, type ReadStream } from "node:fs";
import * as path from "node:path";

export type { ReadStream };

export interface Source {
  stream: Readable;
  label: string;
}

export function open(file: string): Source {
  return {
    stream: createReadStream(file) as ReadStream,
    label: path.basename(file),
  };
}

const source = open(path.join("data", "runs.csv"));
console.log(source.label, typeof source.stream.pipe);

How it works

  1. import type is erased entirely at compile time.
  2. An inline type modifier mixes both in one statement.
  3. export type re-exports without emitting anything.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
472
Tokens
107
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 58 seconds.

Type this snippet

Step 1 of 3 in Modules & declarations, step 5 of 8 in Async & modules.

← Previous Next →