Tutorials / TypeScript: Beginner to Advanced / Objects, interfaces and type aliases

Objects, interfaces and type aliases

16 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. 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:

interfacetype
Object shapesYesYes
Unions, tuples, primitives, mapped typesNoYes
Extendextends&
Declaration merging (same name declared twice is combined)YesNo, a duplicate is an error
Error messages for extension conflictsOften clearerCan 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 object or {} 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 readonly protects at runtime.** It does not.
  • Duplicating types. If two interfaces share fields, extend a base one.
  • **Writing Object with a capital O.** Use object or a specific type.
  • Assuming an interface checks data from an API. It does not. The data is still unchecked.

Try it yourself

  1. Write an interface Book with title, author, optional year and readonly isbn. Create a book and try to change the isbn.
  2. Create Employee that extends Person and adds a salary.
  3. Rewrite the Customer example using type aliases only.
  4. Declare an index signature for a map from product id (string) to quantity (number), and write a function that sums all quantities.
typescript
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