Object types are a fundamental concept in TypeScript, allowing developers to define the structure of objects with specific property types. They provide a way to ensure type safety when working with complex data structures.
In TypeScript, you can define object types using either interfaces or type aliases. Here's a simple example:
interface Person {
name: string;
age: number;
}
type Animal = {
species: string;
legs: number;
}
Both approaches achieve similar results, but interfaces are often preferred for object types due to their extensibility.
Once defined, object types can be used to annotate variables, function parameters, or return types:
function greet(person: Person): string {
return `Hello, ${person.name}! You are ${person.age} years old.`;
}
const john: Person = { name: "John", age: 30 };
console.log(greet(john)); // Output: Hello, John! You are 30 years old.
TypeScript allows you to define optional properties in object types using the ?
operator:
interface Car {
make: string;
model: string;
year?: number;
}
const myCar: Car = { make: "Toyota", model: "Corolla" };
// The 'year' property is optional and can be omitted
You can make properties immutable by using the readonly
modifier:
interface Config {
readonly apiKey: string;
timeout: number;
}
const config: Config = { apiKey: "abc123", timeout: 5000 };
// config.apiKey = "xyz789"; // Error: Cannot assign to 'apiKey' because it is a read-only property
For objects with dynamic property names, you can use index signatures:
interface Dictionary {
[key: string]: string;
}
const colors: Dictionary = {
red: "#FF0000",
green: "#00FF00",
blue: "#0000FF"
};
To deepen your understanding of object types in TypeScript, explore these related topics:
By mastering object types, you'll be well-equipped to create robust and type-safe TypeScript applications.