Typing Object Shapes
Lock down your object structures and level up from JavaScript guesswork to TypeScript precision.
Objects are the backbone of JavaScript. Configs, props, API payloads—you name it, they’re everywhere. But here’s the problem: in JavaScript, object shapes are a free-for-all. We can pass anything, forget properties, or mistype keys, and the interpreter won’t blink until our app explodes at runtime.
TypeScript changes the game. With its object typing system, we stop relying on wishful thinking and start enforcing structure. Want to guarantee that every User
has a name
and an id
, but bio
is optional? TypeScript makes that rock solid. Want to ensure nobody ever overwrites your database-assigned IDs? You can make that possible.
Enforcing object shapes with literal types
Let’s start with the fundamentals. In TypeScript, we can declare object shapes right where we use them. These are called object literal types. They’re perfect when we want to be explicit and tight with our shape.
const user: { name: string; age: number } = {name: "Alice",age: 30,};console.log(user.name);console.log(user);
Here, we’re telling TypeScript: “The user
object must have a name
of type string
and an age
of type number
.” That’s it. Add an extra field? TypeScript complains. Miss one? TypeScript flags it. Assign the wrong type? You guessed it—TypeScript reports an error. And that’s exactly what we want.
Object literal types are like inline contracts. They’re great for quick definitions, but once the shapes grow (and they will), you’ll want to extract them with type
aliases. We’ll get there soon. For now, focus on how this enforces exact structure.
Quick check-in: Can you spot all the violations?
Before we move on, take a look at the object below. TypeScript is already flagging some issues, ...