How to create interfaces and ensure type safety in Nest.js

Learn about creating and using interfaces in NestJS.

overview

NestJS uses TypeScript interfaces to ensure the type safety of your code. Interfaces are a powerful way to represent objects with a particular shape, making your code safer and more predictable. This article details how to create interfaces and ensure type safety in NestJS.

nest.js v10.1.7
nodejs v19.7.0

In addition, all the code created this time is posted on GitHub.

How to create an interface

NestJS allows you to represent an object with a specific shape by creating an interface. Below is an example that creates an interface named User.

/interfaces/user.interface.ts

interface User {
  id: number;
  name: string;
}

This User interface represents an object with two properties: id and name. id is defined to be of numeric type and name to be of string type.

How to use interface

The created interface can be used in each part of the application such as services and controllers.

import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  private users: User[] = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Doe' },
  ];
  getUsers(): User[] {
    return this. users;
  }
  addUser(name: string): void {
    const newUser: User = {
      id: this.users.length + 1,
      name,
    };
    this.users.push(newUser);
  }
  putUser(id: number, name: string): void {
    const index = this.users.findIndex((user) => user.id === Number(id));
    if (index === -1) {
      console.error(`User with id ${id} not found.`);
      return;
    }
    console.log(`Updating user with id ${id} to have name ${name}`);
    this.users[index] = { ...this.users[index], name };
  }
  deleteUser(id: number): void {
    this.users = this.users.filter((user) => user.id !== Number(id));
  }
}

In this example, the UsersService utilizes the User interface and has a private property named users. The users property is an array of type User and each user is guaranteed to have id and name properties.

summary

In this article, you learned how to create interfaces and ensure type safety in NestJS. Interfaces are one of the powerful features of TypeScript that make your code safer and more predictable. The NestJS interface organizes your application’s logic and encourages code reuse.