From single files to libraries
So far each program has lived in one file. Real TypeScript projects are many modules, often with classes that model their core concepts, and they depend on packages written in JavaScript that the compiler has never seen. This lesson covers the three pieces that make that work: TypeScript's additions to classes, how modules are written and resolved, and the declaration files (.d.ts) that carry types for code written in plain JavaScript, including your own library once you publish it.
The JavaScript course's lesson on classes is the background here: classes are syntax over prototypes, and #private fields are enforced by the language. TypeScript adds a layer of compile-time checks on top, a few conveniences, and one important trap.
Typed classes
// Classes in TypeScript: typed fields, access modifiers, interfaces, abstract classes, override.
interface Priced {
priceCents(): number;
}
abstract class Product implements Priced {
static #count = 0;
readonly sku: string; // public by default; cannot be reassigned
protected readonly name: string; // visible in subclasses, not outside
constructor(name: string) {
this.name = name;
this.sku = `P-${++Product.#count}`;
}
abstract priceCents(): number; // subclasses must implement this
label(): string {
return `${this.sku} ${this.name}: ${(this.priceCents() / 100).toFixed(2)}`;
}
}
class Book extends Product {
// A parameter property: declares and assigns the field in one go.
constructor(name: string, private readonly coverPriceCents: number) {
super(name);
}
priceCents(): number {
return this.coverPriceCents;
}
}
class EBook extends Book {
override priceCents(): number { // `override` documents (and checks) intent
return Math.round(super.priceCents() * 0.6);
}
override label(): string {
return `${super.label()} (digital)`;
}
}
class GiftCard implements Priced { // implements: checked against the interface
constructor(private readonly valueCents: number) {}
priceCents(): number {
return this.valueCents;
}
}
const basket: Priced[] = [
new Book("Purple Hibiscus", 1499),
new EBook("Midnight's Children", 1800),
new GiftCard(2500),
];
for (const item of basket) {
console.log(item instanceof Product ? item.label() : `gift card: ${item.priceCents() / 100}`);
}
const total = basket.reduce((sum, item) => sum + item.priceCents(), 0);
console.log("total", (total / 100).toFixed(2));
export {};P-1 Purple Hibiscus: 14.99
P-2 Midnight's Children: 10.80 (digital)
gift card: 25
total 50.79TypeScript's additions, one at a time:
- Field declarations with types (
readonly sku: string;). Under--strict, every field must be definitely assigned in the constructor or have an initialiser (strictPropertyInitialization); a barex: number;that nothing assigns is reported asProperty 'x' has no initializer and is not definitely assigned in the constructor. So an instance can never be seen half-built. - Access modifiers.
publicis the default.protectedmembers are visible in the class and its subclasses;privateonly in the class. Outside,book.namegivesProperty 'name' is protected and only accessible within class 'Product' and its subclasses. - Parameter properties.
constructor(name: string, private readonly coverPriceCents: number)declares a field and assigns the argument to it, saving three lines. They are popular in frameworks such as Angular and NestJS. They are also one of the few TypeScript features that generate code, so they are not allowed witherasableSyntaxOnlyand cannot run under Node's type stripping; teams that rely on stripping write the field out explicitly. implementschecks a class against an interface:GiftCardmust havepriceCents(). It adds nothing at run time and doesn't change the class's type; it only reports a mismatch early, at the class (Class 'Voucher' incorrectly implements interface 'Priced'), rather than wherever an instance is used.abstractclasses cannot be instantiated (Cannot create an instance of an abstract class), and theirabstractmethods must be implemented by every concrete subclass (Non-abstract class 'Poster' does not implement inherited abstract member priceCents from class 'Product'). They suit a family of classes that share code but each fill in a few details.overridemarks a method that replaces a parent's. With the optionnoImplicitOverride, it is required, and a misspelled or removed parent method is caught:This member cannot have an 'override' modifier because it is not declared in the base class 'Book'.
Classes as types, and the private trap
// A class declaration creates a value (the constructor) and a type (its instances).
class Point {
constructor(public x: number, public y: number) {}
length(): number {
return Math.hypot(this.x, this.y);
}
}
// Structural typing applies to classes too: a plain object with the same shape fits.
const p: Point = { x: 3, y: 4, length: () => 5 };
console.log(p.length(), p instanceof Point);
// ...unless the class has private or # members, which make it effectively nominal.
class Money {
#cents: number;
constructor(cents: number) {
this.#cents = cents;
}
plus(other: Money): Money {
return new Money(this.#cents + other.#cents);
}
toString(): string {
return (this.#cents / 100).toFixed(2);
}
}
console.log(String(new Money(250).plus(new Money(199))));
// `typeof Point` is the type of the constructor itself; `new (...) => T` describes any constructor.
type Constructor<T> = new (...args: any[]) => T;
function createMany<T>(Ctor: Constructor<T>, count: number, ...args: unknown[]): T[] {
return Array.from({ length: count }, () => new Ctor(...args));
}
const origins = createMany(Point, 3, 0, 0);
console.log(origins.length, origins[0] instanceof Point);
const PointClass: typeof Point = Point;
console.log(new PointClass(6, 8).length());
// InstanceType and ConstructorParameters read types off a class.
type PointArgs = ConstructorParameters<typeof Point>; // [x: number, y: number]
const args: PointArgs = [5, 12];
console.log(new Point(...args).length());
export {};5 false
4.49
3 true
10
13A class declaration creates two things with one name: a value, the constructor function you call with new, and a type, the shape of its instances. Because typing is structural, a plain object with the same public shape is assignable to the class type, as p shows, even though p instanceof Point is false at run time. That is consistent, but it surprises people from Java or C#.
A private or # member changes this: only instances of the class itself have it, so the class becomes effectively nominal. An imitation of Money is rejected with Property '#cents' is missing in type '{ toString: () => string; }' but required in type 'Money', and plus can safely read other.#cents because other must be a real Money.
typeof Point is the type of the constructor, and new (...args: any[]) => T describes any constructor producing a T, which lets createMany build instances of whatever class it is given. The built-in ConstructorParameters<typeof Point> and InstanceType<typeof Point> read types off a class; lesson eight shows how such utilities are built.
private versus #private
// Describing JavaScript that TypeScript cannot see: `declare` adds types, never code.
// Simulate an old script tag that put a library on the global object, as many still do.
Object.assign(globalThis, {
legacyMath: {
version: "1.4.0",
clamp(x: number, low: number, high: number) {
return Math.min(Math.max(x, low), high);
},
},
});
// The declaration tells the checker what exists at run time. It emits no JavaScript.
declare global {
var legacyMath: {
version: string;
clamp(x: number, low: number, high: number): number;
};
}
console.log(legacyMath.version, legacyMath.clamp(15, 0, 10), legacyMath.clamp(-3, 0, 10));
// TypeScript's private is a compile-time check; # is enforced by JavaScript itself.
class Vault {
private pin = 1234; // hidden from other TypeScript code, but present at run time
#secret = "s3cret"; // truly inaccessible from outside
hasSecret(): boolean {
return this.#secret.length > 0;
}
}
const vault = new Vault();
console.log(Object.keys(vault), JSON.stringify(vault), vault.hasSecret());
export {};1.4.0 10 0
[ 'pin' ] {"pin":1234} trueThe second half of this program shows the trap. TypeScript's private is checked only by the compiler; it is erased, and at run time pin is an ordinary property that Object.keys, JSON.stringify, a debugger or any JavaScript caller can see. A # field is private in JavaScript itself. Use # for anything that must really be hidden; private remains common in older code and in frameworks that predate #, and it is fine for "please don't touch" within a TypeScript code base.
The first half previews the next section: declare global told the compiler that a global legacyMath exists, without producing any code.
When to reach for a class
TypeScript makes classes pleasant, but it doesn't make them obligatory, and idiomatic TypeScript uses them less than Java or C# code does. A rough guide from practice:
- Use a class when many objects share behaviour and guard state with rules: an account whose balance changes only through
deposit, a parser holding its position, a connection pool, a typedEmitter. Private#fields plus methods give a small, enforced interface. - Use plain objects and interfaces for data: API responses, configuration, the props of a UI component, the rows of a table. They serialise to JSON, compare structurally, and need no constructor.
- Use modules of functions for stateless operations. A module already provides privacy (anything not exported) and a namespace (
import * as money from "./money.js"), so a class with only static methods is usually a module in disguise. - Prefer composition to inheritance. One level of
extends, often from anabstractbase, is common and readable; deeper hierarchies make it hard to know which method runs. An interface implemented by several unrelated classes is usually a better seam than a shared parent.
Frameworks shape this too. Angular and NestJS are built around classes with decorators, functions written as @Component(...) or @Injectable() above a class that register it with the framework. TypeScript 5.0 implemented the decorators of the TC39 proposal, which had reached stage 3; the older "experimental" decorators that Angular and NestJS were originally designed around remain available behind the experimentalDecorators option, and the two are not interchangeable. React, by contrast, moved from class components to functions years ago, and most React code bases contain almost no classes at all.
Modules in TypeScript
TypeScript uses the ES module syntax of the JavaScript course's last lesson, with two additions that matter in practice.
File extensions. With "module": "nodenext" (the right setting for code run by Node), TypeScript follows Node's rules, and Node requires the full file name in relative imports. Since the compiled file will be temperature.js, you import ./temperature.js from TypeScript source, even though the file you edit is temperature.ts; TypeScript knows to look at the .ts. Leaving the extension out is an error:
main.ts(1,25): error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './temperature.js'?Projects that go through a bundler such as Vite instead use "moduleResolution": "bundler", which allows extensionless imports as bundlers do. Projects run directly by Node's type stripping import ./temperature.ts and turn on allowImportingTsExtensions (with noEmit), or rewriteRelativeImportExtensions (TypeScript 5.7) if tsc also emits the JavaScript. This is the most confusing corner of TypeScript configuration; the handbook's modules section, linked above, is the authority.
Type-only imports. import type { Reading } from "./temperature.js" imports only a type, and is always erased. With verbatimModuleSyntax on (as tsc --init sets it), TypeScript insists that type-only imports say so, because a tool that removes types file by file, without seeing the other module, cannot know whether a plain import { Unit } names a type or a value:
main.ts(3,10): error TS1484: 'Unit' is a type and must be imported using a type-only import when 'verbatimModuleSyntax' is enabled.The fix is import type { Unit } from ..., or import { type Unit, convert } from ... to mix types and values in one statement. The rule keeps the JavaScript output predictable, and it is what lets fast type-stripping tools work correctly.
Apart from these, modules work exactly as in JavaScript: named exports, default exports, import * as ns, dynamic import(). Types are exported with export type or export interface, and imported like anything else.
Declaration files
Definition— declaration file
A declaration file, ending in .d.ts, contains only types: what a module or a global exports, with no implementation. The compiler reads it in place of the JavaScript it describes. The keyword declare introduces a declaration that promises something exists at run time without creating it.
You will meet declaration files in three ways.
Packages that ship their own types. Most popular packages now include .d.ts files, listed in their package.json (in the types field or in exports), and TypeScript finds them automatically when you import the package.
@types packages. For JavaScript packages without types, the community project DefinitelyTyped publishes them separately under the @types scope: npm install --save-dev @types/express adds types for Express. Node's own built-in modules are typed by @types/node. If no types exist anywhere, you can write a minimal declaration yourself, in a file such as types/legacy-csv.d.ts:
declare module "legacy-csv" {
export interface ParseOptions {
delimiter?: string;
header?: boolean;
}
export function parse(text: string, options?: ParseOptions): string[][];
}Declare only what you use, and keep it honest: these types are trusted without checking, like an assertion. Relatedly, the option skipLibCheck, set by tsc --init, tells the compiler not to type-check the insides of .d.ts files at all. It makes builds much faster and avoids errors from conflicts between third-party type packages, at the cost of not noticing when those files contradict each other; nearly every project turns it on.
Your own library. With "declaration": true, tsc writes a .d.ts beside each .js it emits. For this module:
export type Unit = "C" | "F";
export interface Reading {
value: number;
unit: Unit;
}
/** Converts a reading to the other unit. */
export function convert(reading: Reading): Reading {
return reading.unit === "C"
? { value: reading.value * 9 / 5 + 32, unit: "F" }
: { value: (reading.value - 32) * 5 / 9, unit: "C" };
}
export class Thermometer {
#readings: Reading[] = [];
record(r: Reading): void {
this.#readings.push(r);
}
get count(): number {
return this.#readings.length;
}
}tsc --declaration produces temperature.d.ts:
export type Unit = "C" | "F";
export interface Reading {
value: number;
unit: Unit;
}
/** Converts a reading to the other unit. */
export declare function convert(reading: Reading): Reading;
export declare class Thermometer {
#private;
record(r: Reading): void;
get count(): number;
}Every implementation is gone; signatures, types and documentation comments remain, and the private field is represented by a placeholder (#private;) so the class stays nominal for consumers. Publish the .js and the .d.ts together, and users of your package get full type checking and editor help, whether they write TypeScript or JavaScript.
Augmenting global and module types
Sometimes you need to add to types you don't own: a property your build tool injects into window, a field your middleware adds to a web framework's request object. Declaration merging, from lesson three, does it. Inside a module, declare global { interface Window { analyticsQueue: unknown[] } } extends the browser's Window type; declare module "some-framework" { interface Request { user?: User } } extends an interface exported by a package. The legacyMath program above used the first form with var, which declares a global variable. Use augmentation sparingly and keep it in one well-named file, since it changes types for the whole project.
Common misconceptions
Misconception
"private hides a field." Only from other TypeScript code at compile time. At run time it is an ordinary property, visible to JSON.stringify, Object.keys and any JavaScript. Use # when privacy must be real.
Misconception
"implements makes the class inherit from the interface." It only checks the class against the interface. Nothing is inherited, and the class's own type is unchanged.
Misconception
"Importing ./file.js from TypeScript is wrong, because the file is file.ts." Under nodenext it is required: you write the path of the file that will exist at run time, and TypeScript maps it back to the source.
Misconception
"A .d.ts file is checked against the JavaScript it describes." It is trusted. If the declaration says a function returns a number and the JavaScript returns a string, nothing will notice until run time. Prefer packages that ship types generated from their own source.
Exercises
Some answers depend on what exists at run time and some on what the compiler checks: keep the two apart.
1. Classes, modules and declaration files
StretchComputationalWhat does this print? Write it as Node shows an array.
abstract class Product {
readonly sku: string;
protected readonly name: string;
constructor(name: string) {
this.name = name;
this.sku = "P-1";
}
}
class Book extends Product {
constructor(name: string, private readonly coverPriceCents: number) {
super(name);
}
}
console.log(Object.keys(new Book("Atlas", 2000)));
export {};
2. Classes, modules and declaration files
CoreComputationalWhat does this print?
class Temperature {
constructor(public celsius: number) {}
get fahrenheit(): number {
return this.celsius * 9 / 5 + 32;
}
}
class Reading extends Temperature {
override get fahrenheit(): number {
return Math.round(super.fahrenheit);
}
}
const r = new Reading(21.7);
console.log(r.fahrenheit, r instanceof Temperature, Object.keys(r).join(","));
export {};
3. Classes, modules and declaration files
CoreComputationalWhat does JSON.stringify(new Vault()) give for this class?
class Vault {
private pin = 1234;
#secret = "s3cret";
}
4. Classes, modules and declaration files
CoreComputationalProduct is an abstract class with abstract priceCents(): number. Which of these are compile errors? Choose all that apply.
5. Classes, modules and declaration files
CoreHumanA Node project uses "module": "nodenext" and "type": "module". In main.ts, how do you import convert from the source file temperature.ts in the same folder?
6. Classes, modules and declaration files
Warm-upHumanYou install a popular JavaScript package that ships no type declarations, and import it in TypeScript. What do professionals usually do first?
7. Classes, modules and declaration files
StretchComputationalWith verbatimModuleSyntax enabled, import { Unit } from "./temperature.js"; (where Unit is a type alias) is an error. Why does the option insist on import type?
Further reading and resources
- TypeScript Handbook: Classes · Microsoft
- TypeScript Handbook: Modules (theory and reference) · MicrosoftHow TypeScript models module systems and resolution, in depth.
- TypeScript Handbook: Declaration files · Microsoft
- DefinitelyTypedThe community repository behind the @types packages on npm.
- TSConfig reference: verbatimModuleSyntax · Microsoft