M Logo
๐Ÿ“ TypeScript from Zero ยท Part 15 of 50

TypeScript type vs interface: Optional and readonly Properties

November 6, 2026

Welcome to episode 15 of TypeScript from Zero, a series for complete beginners (no JavaScript needed). Welcome back to TypeScript from zero! Today we describe the shape of an object. We stay in the shop project, with a new file called shapes.ts. Every code block below is the code from the video, ready to copy; run each file to see the output.

Setup

We start in the terminal and open the project in VS Code:

bash
$ touch src/shapes.ts

1. type

With the keyword type we give a name to a shape. A User has a name, which is a string, and an age, which is a number. Then we can say that mia is a User, and TypeScript checks that she has exactly those properties.

ts
type User = {
  name: string;
  age: number;
};
const mia: User = { name: "Mia", age: 30 };
console.log(mia);
bash
$ node src/shapes.ts

2. interface

The keyword interface describes an object shape too. A question mark after a property name makes it optional. So a Book must have a title, but the pages may be missing.

ts
interface Book {
  title: string;
  pages?: number;
}
const dune: Book = { title: "Dune" };
console.log(dune);
bash
$ node src/shapes.ts

3. readonly

The word readonly makes a property read only. We can set it when we create the object, but never change it afterwards. A point on a map, for example, should not move by accident.

ts
interface Point {
  readonly x: number;
  readonly y: number;
}
const p: Point = { x: 1, y: 2 };
console.log(p);
bash
$ node src/shapes.ts

4. Change it

Now we try to change it anyway. Node happily changes x to five. There is no read only rule at run time.

ts
p.x = 5;
console.log(p);
bash
$ node src/shapes.ts

5. tsc

tsc stops us: cannot assign to x, because it is a read only property. The code is TS2540. The protection exists only in TypeScript, so it only works when we run tsc.

bash
$ npx tsc --noEmit

6. Fix

We delete those two lines, and tsc is quiet again.

bash
$ npx tsc --noEmit

7. Which

So type or interface? For object shapes both work, and a good habit is interface for objects, and type for everything else, like unions, which we meet in the next episode.

Recap

Today: type and interface, optional properties, read only properties, and the error for changing one. Next episode: union types and narrowing.

ยฉ 2026 All Rights Reserved By Mahmudul Alam