TypeScript · Lesson 8 of 42
Object types, optional properties, readonly and index signatures
Describe the shape of objects with property types, optional and readonly properties, excess property checks and index signatures for dictionaries.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will describe the shape of any object: which properties it has, which may be missing, which cannot change, and how to type objects used as dictionaries. Objects are the most common value in real programs, so this lesson is one you will use constantly.
An object type
An object type lists property names and the type of each:
const book: { title: string; pages: number } = {
title: "Dune",
pages: 412,
};
console.log(book.title, book.pages);Dune 412Writing the type inline gets long quickly, and the next lessons introduce type aliases and interfaces to give a shape a name. For now, the idea is simple: the type is a list of requirements, and a value must meet all of them.
The compiler enforces the list in both directions. Reading a property that does not exist is an error, and so is leaving a required property out:
const book: { title: string; pages: number } = {
title: "Dune",
};example.ts(1,7): error TS2741: Property 'pages' is missing in type '{ title: string; }' but required in type '{ title: string; pages: number; }'.Optional properties
Add a question mark to make a property optional:
type User = { name: string; nickname?: string };
const a: User = { name: "Asha" };
const b: User = { name: "Ben", nickname: "Benny" };
console.log(a.nickname, b.nickname);undefined BennyWhen you read an optional property, its type is string | undefined, because it might not be there. The compiler makes you deal with that:
type User = { name: string; nickname?: string };
function shout(user: User): string {
return user.nickname.toUpperCase();
}example.ts(4,10): error TS18048: 'user.nickname' is possibly 'undefined'.Fix it with a check, or with the optional chaining operator ?. and a fallback with ??:
type User = { name: string; nickname?: string };
function display(user: User): string {
return user.nickname?.toUpperCase() ?? user.name;
}
console.log(display({ name: "Asha" }), display({ name: "Ben", nickname: "Benny" }));Asha BENNYReadonly properties
Mark a property readonly to forbid changing it after creation:
type Product = { readonly id: number; name: string };
const pen: Product = { id: 1, name: "Pen" };
pen.name = "Gel pen";
pen.id = 2;example.ts(5,5): error TS2540: Cannot assign to 'id' because it is a read-only property.Changing name is fine, but changing id is an error. This is a compile-time promise only; the emitted JavaScript does not freeze the object. It is still very useful for values such as identifiers that must stay constant.
Excess property checks
When you write an object literal directly where a type is expected, TypeScript checks for extra properties. This catches typos:
type Settings = { theme: string; fontSize: number };
const settings: Settings = { theme: "dark", fontSize: 14, colour: "red" };example.ts(3,59): error TS2353: Object literal may only specify known properties, and 'colour' does not exist in type 'Settings'.The check applies to fresh literals only. If you first put the object in a variable and then pass the variable, extra properties are allowed, because the type of the variable is simply a wider object that still has everything required. The rule exists to catch mistakes, not to forbid extra data everywhere.
Index signatures
Sometimes you do not know the property names in advance, for example a count of words or a table of prices by product name. An index signature describes that:
const stock: { [product: string]: number } = {};
stock.pens = 12;
stock["notebooks"] = 5;
console.log(stock);{ pens: 12, notebooks: 5 }It says that any string key maps to a number. The name product is only a label for readers. A later lesson introduces the Record utility type, which writes the same thing more briefly: Record<string, number>.
Be aware that an index signature makes every key look present. stock.anything is typed as a number even if nothing was stored under that key. Where this matters, the noUncheckedIndexedAccess option in tsconfig.json adds undefined to such reads, and a later lesson covers it.
Common mistakes
Marking too many properties optional. Optional properties force a check at every use. Make a property optional only when it truly may be missing.
Thinking readonly makes data immutable. It only stops assignments the compiler can see. Nested objects can still be modified unless they are also readonly.
Being confused by excess property errors. The error is the compiler pointing at a likely typo. Remove the extra property or add it to the type.
Using an index signature for a fixed shape. If you know the keys, list them. Reserve index signatures for real dictionaries.
Exercise
Define a Contact type with a required name, an optional phone and a readonly id. Write a function that prints a contact, using ?. and ?? for the phone. Try to change the id and add an extra property in a literal, and read both errors. Finally, write a dictionary Record-style object counting how many times each word appears in a list of words.
Next: any, unknown, never and void.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.