0
0
Typescriptprogramming~5 mins

Object type annotation inline in Typescript

Choose your learning style9 modes available
Introduction

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.

When you want to quickly describe the shape of an object without creating a separate type or interface.
When passing an object as a function parameter and you want to specify what properties it should have.
When declaring a variable that holds an object and you want to be clear about its structure.
When you want to ensure an object has certain properties with specific types right where you write it.
Syntax
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 :.

Examples
This defines a person object with a name as a string and age as a number.
Typescript
let person: { name: string; age: number } = { name: "Alice", age: 30 };
The function greet expects an object with a name property of type string.
Typescript
function greet(user: { name: string }) {
  console.log(`Hello, ${user.name}!`);
}
This declares a point object with x and y coordinates as numbers.
Typescript
const point: { x: number; y: number } = { x: 10, y: 20 };
Sample Program

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.

Typescript
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);
OutputSuccess
Important Notes

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.

Summary

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.