In this tutorial, we will explore how to create and use objects in TypeScript. TypeScript is a statically typed superset of JavaScript that adds type annotations to help developers catch errors early during development. Understanding how to work with objects in TypeScript is crucial for building robust applications.
Objects are collections of key-value pairs where keys are strings or symbols, and values can be any data type, including other objects. In TypeScript, you can define the structure of an object using interfaces or types, which allows you to enforce specific properties and their types.
In TypeScript, you can define an object's structure using either an interface or a type alias. Both serve similar purposes but have some differences in syntax and usage.
An interface is a way to define the shape of an object. It specifies the names and types of the properties that an object must have.
interface Person {
name: string;
age: number;
email?: string; // Optional property
}
In this example, `Person` is an interface with three properties: `name`, `age`, and `email`. The `email` property is optional because it has a question mark (`?`) after its type.
### Type Aliases
A type alias allows you to give a name to any type. You can use them to define complex types, including object types.
```typescript
type User = {
username: string;
password: string;
isActive: boolean;
};
Here, `User` is a type alias for an object with three properties: `username`, `password`, and `isActive`.
## Examples
Let's explore some practical examples to understand how to use interfaces and type aliases in TypeScript.
### Example 1: Using Interfaces
```typescript
interface Product {
id: number;
name: string;
price: number;
}
const laptop: Product = {
id: 1,
name: 'MacBook Pro',
price: 1299.99
};
console.log(laptop);
Here, we define an Employee type alias and create an object manager that matches the structure defined by the Employee type.
interface Car {
make: string;
model: string;
year?: number; // Optional property
}
const myCar: Car = {
make: 'Toyota',
model: 'Corolla'
};
console.log(myCar);
Here, we extend the Animal interface to create a new Dog interface that includes an additional property breed.
In the next section, we will dive into functions in TypeScript. Functions are fundamental building blocks of any programming language, and understanding how to use them with type annotations is essential for writing clear and maintainable code.
Stay tuned!