0
0
NestJSframework~5 mins

TypeScript-first philosophy in NestJS

Choose your learning style9 modes available
Introduction

Using TypeScript first means writing code with clear types from the start. This helps catch mistakes early and makes your code easier to understand and maintain.

When building a backend API that needs clear data shapes.
When you want your code editor to help you with suggestions and error checks.
When working in a team to keep code consistent and easy to read.
When you want to avoid bugs caused by wrong data types.
When you want to use modern JavaScript features with added safety.
Syntax
NestJS
class User {
  id: number;
  name: string;
  email?: string; // optional

  constructor(id: number, name: string, email?: string) {
    this.id = id;
    this.name = name;
    this.email = email;
  }
}

TypeScript uses : to declare the type of a variable or property.

The ? after a property name means it is optional.

Examples
Basic variable declarations with types.
NestJS
let count: number = 5;
let message: string = 'Hello';
let isActive: boolean = true;
Function with typed parameter and return type.
NestJS
function greet(name: string): string {
  return `Hello, ${name}!`;
}
Using an interface to define the shape of an object.
NestJS
interface Product {
  id: number;
  title: string;
  price: number;
}

const product: Product = { id: 1, title: 'Book', price: 9.99 };
Sample Program

This NestJS controller uses TypeScript types to define the User shape. The getUsers method returns an array of users with clear types, helping catch errors and improving code clarity.

NestJS
import { Controller, Get } from '@nestjs/common';

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

@Controller('users')
export class UsersController {
  @Get()
  getUsers(): User[] {
    return [
      { id: 1, name: 'Alice', email: 'alice@example.com' },
      { id: 2, name: 'Bob' } // email is optional
    ];
  }
}
OutputSuccess
Important Notes

TypeScript-first means you write types before or as you write your code, not after.

Using TypeScript with NestJS improves developer experience with better auto-completion and error checking.

Always keep your types updated as your code changes to avoid confusion.

Summary

TypeScript-first helps catch errors early by using types.

It makes your code easier to read and maintain.

NestJS is built to work well with TypeScript-first philosophy.