TypeScript Object Types
Most data in a JavaScript program lives in objects. An object type describes an object's shape: which properties it has and the type of each one. TypeScript then checks every object you create, pass or read against that shape.
Inline object types
Write the shape in curly braces, separating properties with ; or ,:
const book: { title: string; pages: number; published: boolean } = {
title: "The Tale of Kieu",
pages: 254,
published: true,
};
console.log(`${book.title} has ${book.pages} pages`);The Tale of Kieu has 254 pages
The compiler checks the object in both directions — a missing required property and a property of the wrong type are both errors:
const book: { title: string; pages: number } = {
title: "Dế Mèn",
};
const other: { title: string; pages: number } = {
title: "Notes",
pages: "120",
};main.ts(1,7): error TS2741: Property 'pages' is missing in type '{ title: string; }' but required in type '{ title: string; pages: number; }'.
main.ts(7,3): error TS2322: Type 'string' is not assignable to type 'number'.
Inference
If you create an object literal without an annotation, TypeScript infers its type from the properties. Properties can be updated later, but only with values of the same type, and new properties cannot be added:
const car = { brand: "VinFast", seats: 5 };
car.seats = 7; // fine
car.seats = "seven"; // wrong type
car.color = "red"; // property doesn't exist on the typemain.ts(4,1): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(5,5): error TS2339: Property 'color' does not exist on type '{ brand: string; seats: number; }'.
Optional properties
Add ? after a property name to make it optional. Its type then includes undefined, so you must handle the missing case before using it:
function formatName(person: { first: string; middle?: string; last: string }): string {
if (person.middle) {
return `${person.first} ${person.middle} ${person.last}`;
}
return `${person.first} ${person.last}`;
}
console.log(formatName({ first: "Nguyen", middle: "Van", last: "An" }));
console.log(formatName({ first: "Tran", last: "Binh" }));Nguyen Van An
Tran Binh
Readonly properties
readonly lets you set a property when the object is created but not change it afterwards:
const account: { readonly id: number; balance: number } = { id: 7, balance: 100 };
account.balance += 50;
account.id = 8;main.ts(4,9): error TS2540: Cannot assign to 'id' because it is a read-only property.
Excess property checks
When you assign an object literal directly to a typed variable or parameter, TypeScript also rejects extra properties — they are often typos:
function createUser(options: { username: string; isAdmin?: boolean }) {
return options.username + (options.isAdmin ? " (admin)" : "");
}
console.log(createUser({ username: "hoa", isAdmn: true }));main.ts(5,43): error TS2561: Object literal may only specify known properties, but 'isAdmn' does not exist in type '{ username: string; isAdmin?: boolean | undefined; }'. Did you mean to write 'isAdmin'?
The misspelt isAdmn would otherwise be silently ignored and the user would never become an admin. Note that this check only applies to fresh object literals; an object stored in a variable first is checked structurally (it just needs the required properties). You'll learn why in Structural Typing.
Nested objects and methods
Object types can contain other object types, arrays and functions:
const order: {
id: number;
customer: { name: string; city: string };
items: { sku: string; qty: number }[];
total(): number;
} = {
id: 1001,
customer: { name: "Thu", city: "Hue" },
items: [
{ sku: "TEA-01", qty: 2 },
{ sku: "CUP-09", qty: 4 },
],
total() {
return this.items.reduce((sum, item) => sum + item.qty, 0);
},
};
console.log(order.customer.city, order.items[1].sku, order.total());Hue CUP-09 6
Inline types like this quickly get long. In the Type Aliases & Interfaces lesson you'll learn to give shapes a name and reuse them.
Summary
| Syntax | Meaning |
|---|---|
{ a: string } |
required property |
{ a?: string } |
optional property (string | undefined) |
{ readonly a: string } |
can't be reassigned after creation |
{ greet(): void } |
method |
{ items: string[] } |
property holding an array |
Test yourself
What does ? after a property name mean, as in { age?: number }?
- The property may be null
- The property is optional
- The property is private
- The property's type is unknown
Which error do you get when an object literal contains a property the target type doesn't declare?
- No error
- An excess property error (TS2353/TS2561)
- A runtime TypeError
- TS7006 implicit any
What happens when you assign to a readonly property after creation?
- It works but logs a warning
- A compile-time error (TS2540)
- The value is silently ignored
- A runtime exception is always thrown