Stop 07 · TypeScriptTopics · 2/12

Interfaces

Part of the Frontend Developer Roadmap

In short

Most data in a frontend app is objects: a user, a course, an order. An interface describes exactly what an object must contain, so nobody forgets a field.

A way to define the shape of an object — its properties and their types — so TypeScript can check that objects conform to a contract.

The jaadu mascot holds up a blank ID card and compares it with a card template on the desk.

Think of it like this

The Aadhaar card format

Every Aadhaar card has the same fields: name, date of birth, address, number. A card missing the number isn't valid. An interface is that fixed format for your objects, and TypeScript checks every object against it.

Watch it happen

Student, and Topper built on it

Student
readonly id
name: string
email: string
phone?: string
Topper extends
rank: number

1/5Every Student must have these three fields. Leave one out and TypeScript complains.

The big ideas

What you need to know

Describes a shape

An interface lists property names and their types. Objects must match it to be accepted.

Optional with ?

phone?: string means phone may be missing. Everything without ? is required.

readonly fields

readonly id: number stops anyone from changing the id after the object is created.

extends to build on

interface Admin extends User adds new fields while keeping all of User's.

See it in code

Walk through the code

ts
1interface Student {2  readonly id: number;3  name: string;4  email: string;5  phone?: string;            // optional6}7 8interface Topper extends Student {9  rank: number;10}11 12const riya: Topper = { id: 1, name: "Riya", email: "riya@uni.edu", rank: 1 };13 14riya.id = 2;     // Error: cannot assign to 'id' because it is read-only15function greet(s: Student) { return `Hi ${s.name}`; }

1/4The Student shape: a read-only id, two required strings and one optional phone.

A Topper works anywhere a Student is expected, because it has every Student field plus rank.

Save yourself the pain

Common mistakes

Oops

Making every field optional so errors go away.

Do this instead

Only mark fields optional if they're truly allowed to be missing. Otherwise you just hide bugs.

Oops

Thinking readonly protects data at runtime.

Do this instead

readonly is checked only by TypeScript. Plain JavaScript can still change it. Use Object.freeze for runtime protection.

Your mission

Model your college app

~20 min

Quick check

interface User { name: string; age?: number } Which object is valid?

Go deeper

  1. 1Define an interface for a data model in one of your projects (e.g. `User`).
  2. 2Practice optional (`?`) and readonly properties on an interface.
  3. 3Learn when to use `interface` vs `type` — largely interchangeable, with a few differences.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge