Introduction

Interfaces in TypeScript are a powerful way to define the structure of an object. They allow you to specify the types of properties and methods that an object must have, providing a clear contract for the shape of the data. This helps in maintaining type safety and improving code readability.

Key Concepts

  1. Defining an Interface: An interface is defined using the interface keyword followed by the name of the interface.
  2. Optional Properties: Properties can be marked as optional using the ? symbol.
  3. Readonly Properties: Properties can be marked as readonly using the readonly keyword.
  4. Function Types: Interfaces can also define the types of functions.
  5. Extending Interfaces: Interfaces can extend other interfaces, allowing for the reuse of properties and methods.

Defining an Interface

An interface is defined using the interface keyword. Here is a simple example:

interface Person {
    name: string;
    age: number;
}

In this example, the Person interface defines an object with two properties: name (a string) and age (a number).

Optional Properties

Properties can be marked as optional using the ? symbol. This means that the property may or may not be present in the object.

interface Person {
    name: string;
    age?: number;
}

In this example, the age property is optional.

Readonly Properties

Properties can be marked as readonly using the readonly keyword. This means that the property cannot be changed after the object is created.

interface Person {
    readonly id: number;
    name: string;
    age?: number;
}

In this example, the id property is readonly.

Function Types

Interfaces can also define the types of functions. Here is an example:

interface SearchFunc {
    (source: string, subString: string): boolean;
}

In this example, the SearchFunc interface defines a function that takes two string parameters and returns a boolean.

Extending Interfaces

Interfaces can extend other interfaces, allowing for the reuse of properties and methods.

interface Person {
    name: string;
    age?: number;
}

interface Employee extends Person {
    employeeId: number;
}

In this example, the Employee interface extends the Person interface, adding an employeeId property.

Practical Examples

Example 1: Basic Interface

interface Car {
    make: string;
    model: string;
    year: number;
}

const myCar: Car = {
    make: "Toyota",
    model: "Corolla",
    year: 2020
};

console.log(myCar);

Example 2: Optional and Readonly Properties

interface Book {
    readonly isbn: string;
    title: string;
    author: string;
    publishedYear?: number;
}

const myBook: Book = {
    isbn: "123-456-789",
    title: "TypeScript Basics",
    author: "John Doe"
};

console.log(myBook);

Example 3: Function Types

interface StringValidator {
    (input: string): boolean;
}

const isValidEmail: StringValidator = (email) => {
    const re = /\S+@\S+\.\S+/;
    return re.test(email);
};

console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("invalid-email")); // false

Example 4: Extending Interfaces

interface Animal {
    name: string;
    age: number;
}

interface Dog extends Animal {
    breed: string;
}

const myDog: Dog = {
    name: "Buddy",
    age: 3,
    breed: "Golden Retriever"
};

console.log(myDog);

Exercises

Exercise 1: Define an Interface

Define an interface Student with the following properties:

  • id (number, readonly)
  • name (string)
  • age (number, optional)
  • courses (array of strings)

Create an object student1 that adheres to the Student interface.

Solution

interface Student {
    readonly id: number;
    name: string;
    age?: number;
    courses: string[];
}

const student1: Student = {
    id: 1,
    name: "Alice",
    courses: ["Math", "Science"]
};

console.log(student1);

Exercise 2: Extend an Interface

Define an interface Teacher that extends the Person interface with an additional property subject (string).

Create an object teacher1 that adheres to the Teacher interface.

Solution

interface Person {
    name: string;
    age?: number;
}

interface Teacher extends Person {
    subject: string;
}

const teacher1: Teacher = {
    name: "Mr. Smith",
    age: 40,
    subject: "Mathematics"
};

console.log(teacher1);

Conclusion

In this section, we have learned about interfaces in TypeScript, including how to define them, use optional and readonly properties, define function types, and extend interfaces. Interfaces are a powerful feature in TypeScript that help in defining the structure of objects and ensuring type safety. In the next section, we will explore classes in TypeScript.

© Copyright 2024. All rights reserved