Objects, interfaces and type aliases
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
Describing the shape of an object
Most JavaScript data is objects. TypeScript lets you describe an object's shape, which is the names and types of its properties. There are two ways: an inline type, and a name for the type, either with interface or type.
const book: { title: string; pages: number } = {
title: "Dune",
pages: 412,
};
console.log(book.title);
Writing the shape inline gets old quickly, so we give it a name.
Interfaces
interface User {
id: number;
name: string;
email?: string; // optional
readonly createdAt: Date; // cannot be changed after creation
}
const user: User = {
id: 1,
name: "Sara",
createdAt: new Date(),
};
user.name = "Sara Khan"; // fine
// user.createdAt = new Date(); // Error: Cannot assign to 'createdAt' because it is a read-only property
console.log(user.name, user.email ?? "no email");
An interface is a contract. A value of type User must have id, name and createdAt, may have email, and may not have properties that the interface does not list when written as a fresh object literal. This last rule, called excess property checking, is what catches typos like nme.
Optional properties have the type T | undefined. With strict mode on, TypeScript forces you to handle the missing case before you use them. The ?? operator that we used above does exactly that.
readonly stops assignment through that name. It is a compile-time check only.
Type aliases
A type alias gives a name to any type. For objects, it looks very similar:
type Product = {
id: number;
title: string;
price: number;
tags: string[];
};
const keyboard: Product = { id: 1, title: "Keyboard", price: 3500, tags: ["usb"] };
console.log(keyboard.title);
But type can also name things that interface cannot, such as unions, tuples and primitives:
type ID = string | number;
type Point = [number, number];
type Status = "active" | "inactive";
const id: ID = "abc-123";
const p: Point = [1, 2];
const s: Status = "active";
console.log(id, p, s);
Extending types
Interfaces extend with extends. Type aliases combine with &, called an intersection.
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
type Cat = Animal & { indoor: boolean };
const rex: Dog = { name: "Rex", breed: "Labrador" };
const tom: Cat = { name: "Tom", indoor: true };
console.log(rex.breed, tom.indoor);
Nested objects and arrays of objects
interface Address {
street: string;
city: string;
}
interface Customer {
name: string;
address: Address;
orders: { id: number; total: number }[];
}
const customer: Customer = {
name: "Ali",
address: { street: "Main Road", city: "Lahore" },
orders: [{ id: 1, total: 4500 }],
};
const spent = customer.orders.reduce((sum, o) => sum + o.total, 0);
console.log(customer.address.city, spent);
Index signatures
When you do not know the property names in advance, such as a dictionary, use an index signature:
interface PriceList {
[item: string]: number;
}
const prices: PriceList = { tea: 50, coffee: 120 };
prices.juice = 90;
console.log(prices["tea"], Object.keys(prices).length);
With noUncheckedIndexedAccess turned on, prices["x"] has the type number | undefined, which is the honest answer. For more precise keys, the Record<K, V> utility type is often neater, and we meet it soon.
Interface or type?
For plain object shapes, the two are nearly interchangeable, and teams argue about this more than it deserves. These are the differences that matter:
interface | type | |
|---|---|---|
| Object shapes | Yes | Yes |
| Unions, tuples, primitives, mapped types | No | Yes |
| Extend | extends | & |
| Declaration merging (same name declared twice is combined) | Yes | No, a duplicate is an error |
| Error messages for extension conflicts | Often clearer | Can be harder to read |
My practical rule: use interface for object shapes that describe a thing in your domain, especially those that others may extend, and type for everything else, such as unions and computed types. Pick one convention for your team and keep to it. The compiler is fine either way.
Excess property checks and fresh literals
The "unknown property" error applies only to object literals that you write directly. A variable passed in is not checked this way:
interface Options {
width: number;
}
const extra = { width: 10, height: 20 };
const ok: Options = extra; // fine, extra is not a fresh literal
// const bad: Options = { width: 10, height: 20 }; // Error: unknown property
console.log(ok.width);
This surprises people. It follows from structural typing: extra has a width number, so it fits.
Common mistakes
- **Using
objector{}as a type.** They accept almost anything. Describe the real shape. - Marking too many properties optional. Each one forces checks everywhere. Make a property optional only if it can truly be missing.
- **Assuming
readonlyprotects at runtime.** It does not. - Duplicating types. If two interfaces share fields, extend a base one.
- **Writing
Objectwith a capital O.** Useobjector a specific type. - Assuming an interface checks data from an API. It does not. The data is still unchecked.
Try it yourself
- Write an interface
Bookwith title, author, optional year and readonly isbn. Create a book and try to change the isbn. - Create
Employeethat extendsPersonand adds asalary. - Rewrite the
Customerexample using type aliases only. - Declare an index signature for a map from product id (string) to quantity (number), and write a function that sums all quantities.
interface User {
id: number;
name: string;
email?: string; // optional
readonly createdAt: Date; // cannot be changed after creation
}
const user: User = {
id: 1,
name: "Sara",
createdAt: new Date(),
};
user.name = "Sara Khan"; // fine
// user.createdAt = new Date(); // Error: Cannot assign to 'createdAt' because it is a read-only property
console.log(user.name, user.email ?? "no email");
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account