In JavaScript a typo in a property name isn't an error. user.nmae just gives undefined, the page shows "Hello, undefined", and you only find out when a user complains. TypeScript can catch a typo like that before the code runs, as long as it knows the object's shape.
You write that shape as an object type: which properties it must have, and the type of each one's value. Picture a sign-up form. Some fields are required, some are marked "optional", and some are locked once they're filled in. The object type is the blank form, the object is the filled-in form, and TypeScript checks that what was filled in fits.
Writing an object's shape
let user: { name: string; age: number } = { name: "Budi", age: 17 };
console.log(user.name); // Budi
{ name: string; age: number }after the colon is the object type: each property is writtenname: type, separated by semicolons.- After
=comes the object itself: each property is writtenname: value, separated by commas. - TypeScript knows
user.nameis astring. A typo likeuser.nmaeis rejected:Property 'nmae' does not exist on type '{ name: string; age: number; }'. ts(2339).
Missing, wrong, or extra
Here's what TypeScript says about four objects under the type { name: string; age: number }, the same as in the Lab:
| Object | What TypeScript says |
|---|---|
{ name: "Budi", age: 17 } |
no error |
{ name: "Budi", age: "17" } |
Type 'string' is not assignable to type 'number'. ts(2322) |
{ name: "Budi" } |
Property 'age' is missing in type '{ name: string; }' but required in type '{ name: string; age: number; }'. ts(2741) |
{ name: "Budi", age: 17, hobby: "futsal" } |
Object literal may only specify known properties, and 'hobby' does not exist in type '{ name: string; age: number; }'. ts(2353) |
- Wrong type:
"17"is text, butageasks for a number. - Missing: there's no
age, but it's required. - Extra:
hobbyisn't in the type, so it's rejected, even thoughnameandageare both there. An object written out directly can't have properties the type doesn't know, because an unknown property is usually a typo, likeaegwhen you meantage.
Optional properties with ?
let user: { name: string; age?: number } = { name: "Budi" };
console.log(user.age); // undefined
- A
?after a property's name makes that property optional: it may be there or not. The object withoutageis accepted now. - Since it might not be there, the type of
user.agebecomesnumber | undefined, read as "number or undefined". The|sign is covered in the Union & Literal lesson. - So before using it as a number, TypeScript wants you to check it.
user.age.toFixed(0)is rejected:'user.age' is possibly 'undefined'. ts(18048).
readonly: locked once it's filled in
let user: { readonly name: string; age: number } = { name: "Budi", age: 17 };
user.age = 18; // allowed
user.name = "Ani";
readonlyin front of a property's name means its value can only be read once the object is made.- The last line is rejected:
Cannot assign to 'name' because it is a read-only property. ts(2540). - Just like
readonlyon arrays, this is only checked before the code runs. The word is gone from the compiled JavaScript, and if it runs anyway,namereally does become"Ani".
⚠️ Why is my object rejected, or let through?
- Writing the type as the value.
let user = { name: string, age: number };is rejected with'string' only refers to a type, but is being used as a value here. ts(2693). The type goes after a colon next to the variable's name, the values after=. - A number written as text. In the exercise,
user.ageis graded as the number17.age: "17"fails twice: its value isn't a number, and the exercise's TypeScript checker rejects it witherror TS2322. - Leaving out the type annotation.
let user = { name: "Budi", age: 17 };is valid, TypeScript works out the shape by itself. But this exercise checks that your code uses a type annotation, so write the object type. - Thinking
?andreadonlyapply while the code runs. Both are only rules for TypeScript. Data from a server with nonamestill gets in without a complaint.
TL;DR: An object type is written { name: string; age: number } after the colon, then the object { name: "Budi", age: 17 } after =. A property with the wrong type (ts(2322)), a missing one (ts(2741)), or an extra one (ts(2353)) is rejected. age?: number makes a property optional, and its type becomes number | undefined, so check it before use. readonly name: string stops name from being changed (ts(2540)). All of these rules are only checked before the code runs.
⚡ Write the object's shape
Write:
let user: { name: string; age: number } = { name: "Budi", age: 17 };
console.log(user.name); // Budi
Meaning: After the colon comes the object type, its properties separated by semicolons. After = comes the object itself, separated by commas. Because TypeScript knows the shape, a typo like user.nmae is rejected straight away.
⚡ Missing or extra, both are rejected
Guess first: { name: "Budi", age: 17, hobby: "futsal" } already has name and age. Does it pass?
Rejected: 'hobby' does not exist in type. An object written out directly can't have properties the type doesn't know, because a stray property is usually a typo.
Meaning: An object without age is rejected too, because age is required. age: "17" is rejected because it's text, and age wants a number.
⚡ Optional properties with ?
Write:
let user: { name: string; age?: number } = { name: "Budi" };
console.log(user.age); // undefined
Meaning: ? means the property may be there or not. The type of user.age becomes number | undefined, so TypeScript wants a check before it's used as a number.