Last Updated : 23 Jan, 2025
TypeScript object types define the structure of objects by specifying property types, ensuring type safety and clarity when passing objects as function parameters.
interface Person {
name: string;
age: number;
address?: string; // Optional property
}
function greet(person: Person): string {
return `Hello, ${person.name}!`;
}
const user: Person = {
name: "Alice",
age: 30
};
console.log(greet(user));
Output:
Hello, Alice!
More Example of TypeScript Object Types
Defining a Car Object JavaScript
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.Nested Object Types for a Book JavaScript
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 DoeFunction Parameter with Object Type JavaScript
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: 50Best Practices for Using TypeScript Object Types
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4