Finally, Autocomplete You Can Trust: Describing Objects
What's in this object again?
In JavaScript, you work with objects all the time. But how often have you done this?
// some function that returns a user object
const user = getUser();
// ...later in the code...
console.log(user.nmae); // Typo! Should be 'name'
console.log(user.id); // Was it 'id' or 'userId'? Or 'ID'?
You type user. and your editor gives you... nothing. A blank slate. You have to guess the property names, remember their exact spelling and capitalization, and hope you get it right. When you get it wrong, you get the dreaded TypeError: Cannot read properties of undefined at runtime, because you tried to access a property on a value that was undefined due to your typo.
This is arguably the single biggest source of daily frustration for JS developers. And this is where TypeScript delivers its most spectacular win.
How to Describe an Object's Shape with a type Alias
With TypeScript, you can describe the "shape" of an object ahead of time. The most common way to do this is with a type alias.
Think of it like a blueprint for an object. You're telling TypeScript, "Any object that claims to be a User must have these specific properties with these specific types."
Exercise 1: Get Perfect Autocomplete
- We've defined a
typealias calledUser. - In the
newUserobject, place your cursor afterid: 1,and pressCtrl+Space(orCmd+Space). Notice how the editor suggestsnameandisVerifiedfor you. - Start typing
nand press Enter to autocompletename. Assign it a string value. - After the comma, press
Ctrl+Spaceagain. The editor now only suggestsisVerified. Add that property and assign it a boolean value.
The moment you told TypeScript that newUser should be of type User (using : User), you unlocked perfect, reliable autocomplete. The guessing game is over.
Typos and Errors, Begone!
This isn't just about convenience. It's about correctness. TypeScript will now yell at you if you deviate from the blueprint.
Exercise 2: Find and Fix the Errors
- The
brokenUserobject below has two errors. Red squiggles highlight them. - Hover over the first error on
userId. TypeScript tells you thatuserIddoesn't exist in theUsertype. The correct property isid. - Hover over the second error on
isVerified. TypeScript tells you that you're trying to assign astringto a property that expects aboolean. - Fix both errors so that the
brokenUserobject correctly matches theUsertype.
Click to see the solution
type User = {
id: number;
name: string;
isVerified: boolean;
};
// ✅ Correct!
const brokenUser: User = {
id: 2,
name: "SuperMario",
isVerified: true,
};
By spending a few seconds defining the shape of your data, you've created a safety net that eliminates a huge category of common bugs. This is the core loop of working with TypeScript: describe your data's shape, then let the compiler help you use it correctly.