Objects
Objects
Section titled βObjectsβWhat it means
Section titled βWhat it meansβ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).
Examples
Section titled βExamplesβ// Inline object typefunction printUser(user: { name: string; age: number }) { console.log(`${user.name} is ${user.age}`);}
// Type alias, reusabletype 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 timetype 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 typestype PartialUser = Partial<User>; // every property becomes optionaltype UserPreview = Pick<User, "name" | "id">; // only a subset of propertiesCommon mistake
Section titled βCommon mistakeβ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 reassignconfig.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 itQuick practice
Section titled βQuick practiceβ-
What does
readonlyactually prevent?Answer
Reassigning that specific property after the object is created β it does not make nested objects or arrays inside that property immutable. -
Whatβs an index signature used for?
Answer
Describing 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. -
What does
Partial<User>do to a type?Answer
Produces a new type with every property ofUsermade optional β useful for things like "patch" update objects where only some fields are provided.