Want a faster signal before interviews? Take the Interview Ready Check →

DAY 5 OF 30

Object types, optional and readonly

Yesterday, in one sentence

What is a union type in TypeScript?

Interview question

What is the difference between string | boolean[], (string | boolean)[] and [boolean, string]?

You add a type annotationType Annotation to an object by listing its property names and their types inside braces. It looks just like a JavaScript object, but with types instead of values. This is called an object type, and it describes the shape the object must have.

let user: { id: number; name: string } = { id: 1, name: "Sam" };

user.name = "Alex"; // ok
user.name = 5; // ❌ Type 'number' is not assignable to type 'string'
user.email = "a@b.com"; // ❌ Property 'email' does not exist on this type

Adding a ? to a property name in an object type makes it an optional property, so the object does not have to include it. Reading an optional property gives you a union typeUnion Type of the declared type and undefined, because the property might not be there.

let user: { id: number; nickname?: string } = { id: 1 };

user.nickname; // string | undefined

Putting readonly in front of a property name in an object type stops that property being reassigned after the object is created.

let user: { readonly id: number; name: string } = { id: 1, name: "Sam" };

user.name = "Alex"; // ok
user.id = 2; // ❌ Cannot assign to 'id' because it is a read-only property

You might be wondering how readonly differs from const.

In const user: { readonly name: string } = { name: 'Magneto' }, const stops the variable user being reassigned and readonly stops the property name being reassigned.

const stops the variable being reassigned. readonly stops a property inside the object being reassigned. They protect different things, and you can use both together.

Check yourself

Given let user: { id: number; nickname?: string }, what is the type of user.nickname?
What does ? do to a property in an object type, and what does readonly do?