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
import typeis erased entirely at compile time.- An inline
typemodifier mixes both in one statement. export typere-exports without emitting anything.
Keywords and builtins used here
ReadableasconstcreateReadStreamexportfromfunctionimportinterfacereturnstringtype
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.
Step 1 of 3 in Modules & declarations, step 5 of 8 in Async & modules.