Skip to content

Objects

TypeScript can describe the shape of an object literal inline ({ name: string; age: number }), via a type alias, or via an interface. It also supports utility modifiers like readonly (prevents reassignment after creation) and index signatures (for objects whose exact keys aren’t known ahead of time, like a lookup map).

// Inline object type
function printUser(user: { name: string; age: number }) {
console.log(`${user.name} is ${user.age}`);
}
// Type alias, reusable
type User = { name: string; age: number; readonly id: string };
const user: User = { id: "u1", name: "Alice", age: 30 };
// user.id = "u2"; // Error: cannot assign to 'id' because it's readonly
// Index signature -- keys aren't known ahead of time
type Scores = { [playerName: string]: number };
const scores: Scores = { alice: 90, bob: 85 };
scores["carol"] = 78; // fine -- any string key is allowed
// Utility types built on object types
type PartialUser = Partial<User>; // every property becomes optional
type UserPreview = Pick<User, "name" | "id">; // only a subset of properties

Marking a property readonly and assuming it makes the whole object deeply immutable β€” readonly only prevents reassigning that specific property; if the property’s value is itself an object or array, its contents can still be mutated.

type Config = {
readonly settings: { theme: string };
};
const config: Config = { settings: { theme: "dark" } };
// config.settings = { theme: "light" }; // Error: readonly, can't reassign
config.settings.theme = "light"; // No error! nested mutation still works
// For true deep immutability, every nested level needs its own readonly,
// or use a utility type designed for it
  1. What does readonly actually prevent?

    AnswerReassigning that specific property after the object is created β€” it does not make nested objects or arrays inside that property immutable.
  2. What’s an index signature used for?

    AnswerDescribing an object type where the exact set of keys isn't known in advance, but all keys share a common value type β€” like { [key: string]: number } for a lookup table.
  3. What does Partial<User> do to a type?

    AnswerProduces a new type with every property of User made optional β€” useful for things like "patch" update objects where only some fields are provided.