We use object type annotation inline to tell TypeScript what kind of data an object should have. This helps catch mistakes early and makes code easier to understand.
Object type annotation inline in Typescript
let variableName: { property1: type1; property2: type2; } = { property1: value1, property2: value2 };The object type is written inside curly braces { } with property names and their types separated by semicolons.
This annotation goes right after the variable name and colon :.
person object with a name as a string and age as a number.let person: { name: string; age: number } = { name: "Alice", age: 30 };
greet expects an object with a name property of type string.function greet(user: { name: string }) { console.log(`Hello, ${user.name}!`); }
point object with x and y coordinates as numbers.const point: { x: number; y: number } = { x: 10, y: 20 };
This program defines a function printBook that takes an object with title and pages. It then prints these details. We create myBook with matching properties and call the function.
function printBook(book: { title: string; pages: number }) { console.log(`Title: ${book.title}`); console.log(`Pages: ${book.pages}`); } const myBook = { title: "Learn TypeScript", pages: 250 }; printBook(myBook);
Inline object type annotations are great for quick checks but can get hard to read if the object has many properties.
For bigger objects, consider using type or interface to keep code clean.
Inline object type annotation tells TypeScript the shape of an object right where you use it.
It helps catch errors and makes code easier to understand.
Use it for small objects or function parameters for quick type checks.