Object types specify the expected structure of an object by defining its properties and their data types.
- Define the shape of an object.
- Support required and optional properties.
- Ensure type-safe object creation and usage.
Example of Object Types in TypeScript
The following example demonstrates how object types define the required and optional properties of an object.
interface Person {
name: string;
age: number;
address?: string; // Optional property
}
function greet(person: Person): string {
return `Hello, ${person.name}!`;
}
const user: Person = {
name: "Alen",
age: 30
};
console.log(greet(user));
Output:
Hello, Alen!- Person defines an object type with name and age as required properties.
- address is an optional property.
- The greet() function accepts only objects that match the Person type.
Example 1: Defining a Car Object
Object types ensure that objects follow a predefined structure.
interface Car {
make: string;
model: string;
year: number;
electric?: boolean; // Optional property
}
const myCar: Car = {
make: "Tesla",
model: "Model S",
year: 2022,
electric: true
};
console.log(`I drive a ${myCar.year} ${myCar.make} ${myCar.model}.`);
Output:
I drive a 2022 Tesla Model S.- Car defines the structure of a car object.
- make, model, and year are required properties.
- electric is optional.
Example 2: Nested Object Types for a Book
Object types can contain other object types to represent complex data structures.
interface Author {
name: string;
birthYear: number;
}
interface Book {
title: string;
author: Author;
pages: number;
genre?: string; // Optional property
}
const myBook: Book = {
title: "TypeScript Basics",
author: {
name: "Jane Doe",
birthYear: 1980
},
pages: 350
};
console.log(`${myBook.title} by ${myBook.author.name}`);
Output:
TypeScript Basics by Jane Doe- Author defines the structure of the author object.
- Book contains a nested object of type Author.
- myBook follows the structure defined by both object types.
Example 3: Function Parameter with Object Type
Object types can be used as function parameters to ensure the expected object structure is passed.
interface Rectangle {
width: number;
height: number;
}
function calculateArea(rect: Rectangle): number {
return rect.width * rect.height;
}
const myRectangle: Rectangle = {
width: 10,
height: 5
};
console.log(`Area: ${calculateArea(myRectangle)}`);
Output:
Area: 50- Rectangle defines the required properties of the object.
- calculateArea() accepts only a Rectangle object.
- The function calculates the area using the object's properties.