TypeScript objects, interfaces, type aliases and classes
Most data in a TypeScript program is objects: orders, customers, order lines. This third basics tutorial shows how to describe their shapes, first inline, then as named interfaces and type aliases, how to choose between those two, and how to write classes with typed fields, constructors and access modifiers. It assumes you have done Types and inference and Functions and generics.
What you’ll build
Section titled “What you’ll build”The data model for a shopping cart in the invented OrdersPortal shop: an OrderLine and Customer described with interfaces, a CartEvent union described with a type alias, and a Cart class that keeps its lines private, validates what is added and reports a total.
Prerequisites
Section titled “Prerequisites”The folder from the earlier tutorials: Node.js 22.18 or later, a package.json with "type": "module", and TypeScript installed (the samples were compiled with TypeScript 7.0.2). Save each sample as cart.ts, compile it with npx tsc --module nodenext cart.ts, and run node cart.js. Compiler errors are quoted as tsc prints them, without the file and position prefix.
Object types
Section titled “Object types”An object type lists property names and their types between braces: { sku: string; quantity: number }. You can write it inline, in a parameter or variable annotation, but most object types are given a name, as in the next section. Two modifiers are used all the time. A ? after the name makes a property optional, so it may be missing and its type includes undefined. readonly before the name stops the property from being reassigned after the object is created.
TypeScript checks object literals strictly: a literal assigned to an object type must have every required property and no unknown ones, which catches typos such as quantiy. Objects used as dictionaries, whose keys are not known in advance, use an index signature, { [sku: string]: number }, or the equivalent Record<string, number>; see Index signatures.
function lineLabel(line: { sku: string; quantity: number; giftNote?: string }): string { const note = line.giftNote ? ` (gift: ${line.giftNote})` : ""; return `${line.quantity} x ${line.sku}${note}`;}
const product: { readonly sku: string; title: string; price: number } = { sku: "SKU-RED-01", title: "Red mug", price: 9.5,};product.price = 8.5; // allowed: price is not readonly
const stock: Record<string, number> = { "SKU-RED-01": 12 };stock["SKU-BLU-02"] = 3;
console.log(lineLabel({ sku: product.sku, quantity: 2 }));console.log(lineLabel({ sku: "SKU-BLU-02", quantity: 1, giftNote: "Happy birthday" }));console.log(product.price, Object.keys(stock));Output:
2 x SKU-RED-011 x SKU-BLU-02 (gift: Happy birthday)8.5 [ 'SKU-RED-01', 'SKU-BLU-02' ]Writing product.sku = "SKU-X"; fails with error TS2540: Cannot assign to 'sku' because it is a read-only property., and the typo lineLabel({ sku: "SKU-RED-01", quantiy: 2 }) fails with error TS2561: Object literal may only specify known properties, but 'quantiy' does not exist in type '{ sku: string; quantity: number; giftNote?: string | undefined; }'. Did you mean to write 'quantity'?
Pitfalls:
readonlyis shallow. Areadonly settings: { theme: string }property cannot be replaced, butsettings.themecan still be changed.- Optional is not the same as nullable.
giftNote?: stringmay be missing;giftNote: string | nullmust be present and may benull. Pick the one that matches your data.
Interfaces
Section titled “Interfaces”An interface gives an object type a name: interface Customer { id: string; email?: string }. Use the name anywhere a type is expected. Interfaces can extend one or more other interfaces to add properties, and can describe methods (total(): number) and even callable values.
TypeScript’s type system is structural: any object with the required properties satisfies an interface, whether it is an object literal, a parsed and validated JSON value or a class instance. Nothing has to declare that it implements the interface. This differs from C# or Java, where a class must name the interfaces it implements. It also means an interface does not exist at run time; it cannot be used with instanceof.
interface Customer { id: string; displayName: string; email?: string;}
interface OrderLine { readonly sku: string; quantity: number; unitPrice: number;}
interface GiftLine extends OrderLine { giftNote: string;}
interface PriceFormatter { format(amount: number): string;}
const euro: PriceFormatter = { format: (amount) => `${amount.toFixed(2)} EUR`,};
function describeLine(line: OrderLine, formatter: PriceFormatter): string { return `${line.quantity} x ${line.sku} = ${formatter.format(line.quantity * line.unitPrice)}`;}
const customer: Customer = { id: "C-1", displayName: "Ada Lopez" };const gift: GiftLine = { sku: "SKU-RED-01", quantity: 2, unitPrice: 9.5, giftNote: "Thanks!" };
console.log(customer.displayName, customer.email ?? "(no email)");console.log(describeLine(gift, euro)); // a GiftLine is also an OrderLineOutput:
Ada Lopez (no email)2 x SKU-RED-01 = 19.00 EURCreating const customer: Customer = { id: "C-1" }; fails with error TS2741: Property 'displayName' is missing in type '{ id: string; }' but required in type 'Customer'.
Pitfalls:
- Extra properties are allowed on non-literal values.
describeLine(gift, euro)accepts aGiftLinebecause it has everythingOrderLineneeds; only fresh object literals are checked for unknown properties. - Interfaces describe, they do not validate. Data from an API is not a
Customerbecause you annotated it; check it first (see Type narrowing).
Types versus interfaces
Section titled “Types versus interfaces”A type alias gives a name to any type: type OrderId = string, type CartEvent = AddedEvent | RemovedEvent, or an object type, type Customer = { id: string }. For object shapes, type aliases and interfaces are nearly interchangeable. The differences that matter in practice:
- Only a type alias can name a union, a tuple, a primitive or a type built with mapped and conditional types.
- Interfaces with the same name in the same scope merge into one (declaration merging); declaring a type alias twice is an error. Merging is how libraries let you extend their types.
- Interfaces extend with
extends, which reports conflicting properties at the declaration; type aliases combine with&(an intersection), where conflicts turn intoneversilently.
The TypeScript handbook’s heuristic is to use interface until you need a feature only type has. In practice: an interface for object shapes, especially public ones that others may extend, and a type alias for everything else. Be consistent within a codebase; the choice rarely matters as much as reviews suggest.
interface Customer { id: string; displayName: string;}
type OrderId = string;type CartEvent = | { type: "added"; sku: string; quantity: number } | { type: "removed"; sku: string };type Money = readonly [amount: number, currency: "EUR" | "USD"];
type Timestamped = { at: string };type LoggedEvent = CartEvent & Timestamped;
function describeEvent(event: LoggedEvent): string { return event.type === "added" ? `${event.at} added ${event.quantity} x ${event.sku}` : `${event.at} removed ${event.sku}`;}
const owner: Customer = { id: "C-1", displayName: "Ada Lopez" };const lastOrder: OrderId = "ORD-1042";const total: Money = [19, "EUR"];const events: LoggedEvent[] = [ { type: "added", sku: "SKU-RED-01", quantity: 2, at: "09:30" }, { type: "removed", sku: "SKU-RED-01", at: "09:31" },];
console.log(owner.displayName, lastOrder, total.join(" "));events.forEach((e) => console.log(describeEvent(e)));Output:
Ada Lopez ORD-1042 19 EUR09:30 added 2 x SKU-RED-0109:31 removed SKU-RED-01Trying to write the union as an interface is not valid syntax at all; declaring type OrderId = string; twice fails with error TS2300: Duplicate identifier 'OrderId'.
Pitfalls:
- Do not convert everything in a big refactor. Mixing interfaces and type aliases for object shapes is harmless; pick a convention for new code.
- Accidental merging. An interface named like a global, such as
EventorRequest, in a script file merges with the DOM’s; keep code in modules.
Classes
Section titled “Classes”Classes are a JavaScript feature; TypeScript adds type annotations for fields, constructor parameters and methods, plus checks. Under strict mode, every field must be initialized in its declaration or the constructor. Access modifiers control who may use a member: public (the default), protected (the class and its subclasses) and private (the class only). readonly fields can be set only in the declaration or the constructor.
These modifiers are compile-time checks only: in the JavaScript output, a private field is an ordinary property. For privacy enforced at run time, JavaScript has #private fields, which TypeScript supports and which this tutorial’s Cart uses for its lines. A constructor parameter with a modifier, constructor(public readonly customerId: string), is a parameter property: shorthand that declares and assigns the field in one step.
A class can implements an interface, asking the compiler to check that the class has everything the interface requires. More on classes, including abstract classes, override and decorators, is in Classes and decorators; the runtime model is on the JavaScript classes page.
interface OrderLine { readonly sku: string; quantity: number; unitPrice: number;}
interface Totalled { total(): number;}
class Cart implements Totalled { #lines: OrderLine[] = []; private couponRate = 0;
constructor(public readonly customerId: string) {}
add(line: OrderLine): void { if (line.quantity <= 0) throw new RangeError(`Invalid quantity for ${line.sku}`); const existing = this.#lines.find((l) => l.sku === line.sku); if (existing) existing.quantity += line.quantity; else this.#lines.push({ ...line }); }
applyCoupon(code: string): boolean { this.couponRate = code === "WELCOME10" ? 0.1 : 0; return this.couponRate > 0; }
total(): number { const sum = this.#lines.reduce((acc, l) => acc + l.quantity * l.unitPrice, 0); return Math.round(sum * (1 - this.couponRate) * 100) / 100; }
get lineCount(): number { return this.#lines.length; }}
class GiftCart extends Cart { constructor(customerId: string, public readonly giftNote: string) { super(customerId); }
override total(): number { return super.total() + 2.5; // gift wrapping }}
const cart = new GiftCart("C-1", "Happy birthday");cart.add({ sku: "SKU-RED-01", quantity: 2, unitPrice: 9.5 });cart.add({ sku: "SKU-RED-01", quantity: 1, unitPrice: 9.5 });cart.add({ sku: "SKU-BLU-02", quantity: 1, unitPrice: 4.99 });console.log(cart.customerId, cart.lineCount, cart.applyCoupon("WELCOME10"), cart.total());console.log(JSON.stringify(cart)); // #lines is not serialized; private couponRate isOutput:
C-1 2 true 32.64{"customerId":"C-1","couponRate":0.1,"giftNote":"Happy birthday"}Reading cart.couponRate outside the class fails with error TS2341: Property 'couponRate' is private and only accessible within class 'Cart'., yet JSON.stringify still includes it, which shows that private is a compile-time rule. Declaring private couponRate: number; without the = 0 fails with error TS2564: Property 'couponRate' has no initializer and is not definitely assigned in the constructor.
Pitfalls:
privateis not secret. Use#privatefor anything that must not leak into logs or JSON.privateversusprotected. A subclass cannot use aprivatemember of its base class; make itprotectedif subclasses need it.
Complete working result
Section titled “Complete working result”The cart model from this tutorial in one file, with an event log that uses the union type:
interface Customer { id: string; displayName: string; email?: string;}
interface OrderLine { readonly sku: string; quantity: number; unitPrice: number;}
type CartEvent = | { type: "added"; sku: string; quantity: number } | { type: "coupon"; code: string; accepted: boolean };
class Cart { #lines: OrderLine[] = []; #couponRate = 0; readonly events: CartEvent[] = [];
constructor(public readonly customer: Customer) {}
add(line: OrderLine): this { if (line.quantity <= 0) throw new RangeError(`Invalid quantity for ${line.sku}`); const existing = this.#lines.find((l) => l.sku === line.sku); if (existing) existing.quantity += line.quantity; else this.#lines.push({ ...line }); this.events.push({ type: "added", sku: line.sku, quantity: line.quantity }); return this; }
applyCoupon(code: string): this { const accepted = code.toUpperCase() === "WELCOME10"; this.#couponRate = accepted ? 0.1 : 0; this.events.push({ type: "coupon", code, accepted }); return this; }
total(): number { const sum = this.#lines.reduce((acc, l) => acc + l.quantity * l.unitPrice, 0); return Math.round(sum * (1 - this.#couponRate) * 100) / 100; }}
function describe(event: CartEvent): string { switch (event.type) { case "added": return `+${event.quantity} ${event.sku}`; case "coupon": return `coupon ${event.code} ${event.accepted ? "accepted" : "rejected"}`; }}
const cart = new Cart({ id: "C-1", displayName: "Ada Lopez", email: "ada@example.test" }) .add({ sku: "SKU-RED-01", quantity: 2, unitPrice: 9.5 }) .add({ sku: "SKU-BLU-02", quantity: 1, unitPrice: 4.99 }) .applyCoupon("SPRING") .applyCoupon("welcome10");
try { cart.add({ sku: "SKU-GRN-03", quantity: 0, unitPrice: 3 });} catch (error) { console.log(error instanceof RangeError ? error.message : error);}
console.log(cart.events.map(describe).join("; "));console.log(`${cart.customer.displayName} pays ${cart.total().toFixed(2)} EUR`);Output:
Invalid quantity for SKU-GRN-03+2 SKU-RED-01; +1 SKU-BLU-02; coupon SPRING rejected; coupon welcome10 acceptedAda Lopez pays 21.59 EURTroubleshooting
Section titled “Troubleshooting”| Error | What it means | Fix |
|---|---|---|
TS2741: Property 'x' is missing in type ... but required in type ... |
An object lacks a required property. | Add it, or mark the property optional if it really can be missing. |
TS2561 or TS2353: Object literal may only specify known properties |
A literal has a property the type does not declare, often a typo. | Fix the name, or add the property to the type. |
TS2540: Cannot assign to 'x' because it is a read-only property. |
A readonly property is reassigned. |
Create a new object, or remove readonly if mutation is intended. |
TS2564: Property 'x' has no initializer and is not definitely assigned in the constructor. |
A class field is never set. | Initialize it in the declaration or the constructor. |
TS2341: Property 'x' is private and only accessible within class 'Y'. |
Code outside the class uses a private member. |
Add a public method or getter, or make it protected for subclasses. |
Check your understanding
Section titled “Check your understanding”- What is the difference between
email?: stringandemail: string | null? - Does an object need to declare that it implements an interface to be used where that interface is expected?
- Name two things a type alias can describe that an interface cannot.
- Why does
JSON.stringify(cart)include aprivatefield but not a#privateone?
Answers: (1) The first may be missing (and is then undefined); the second must be present and may be null. (2) No; TypeScript is structural, so having the required members is enough. (3) Any two of: unions, tuples, primitives, mapped and conditional types. (4) private is erased at compile time and the field is an ordinary property; #private fields are hidden by the JavaScript runtime.
Next steps
Section titled “Next steps”Continue with Modules and compilation, which splits this model across files and sets up a tsconfig.json.
Related pages
Section titled “Related pages”- TypeScript basics overview
- Core type system: interfaces, unions, intersections and index signatures in depth.
- Classes and decorators: access modifiers, abstract classes,
overrideand decorators.