Skip to main content

Object Basics

Typing an object

An object type lists each property and its type. Access a property that isn't in the type and TypeScript throws an error — that's the safety.

const user: { name: string; age: number } = { name: "Ajay", age: 23 };

user.name; // Valid: user.email; // Error: Property 'email' does not exist on type '{ name: string; age: number }'

Three ways to declare an object's type

1. Inline (object literal type) — the type written directly at the usage site.

function printUser(user: { name: string; age: number }) {}

2. type alias — a named, reusable shape.

type User = { name: string; age: number };
function printUser(user: User) {}

3. interface — also a named, reusable object shape.

interface User { name: string; age: number }
function printUser(user: User) {}

In production apps, avoid inline object types. Give the shape a name with type or interface — it's reusable, it makes errors readable (User instead of a giant inline blob), and it documents intent.

Optional properties

Mark a property optional with ?. Then it may be present or missing:

type User = { name: string; isAdmin?: boolean };
const a: User = { name: "Ajay" }; // Valid: isAdmin omitted
const b: User = { name: "Ravi", isAdmin: true }; // Valid: ```