0
0
Typescriptprogramming~5 mins

Required type in Typescript

Choose your learning style9 modes available
Introduction

The Required type makes sure all properties in an object are needed. It helps catch missing parts early.

When you want to make sure an object has all its properties filled.
When you get an object with some optional properties but want to require them later.
When you want to avoid errors from missing data in your program.
When you want to enforce complete data for functions or components.
Syntax
Typescript
Required<Type>

Type is the object type you want to change.

This creates a new type where all properties are no longer optional.

Examples
Here, User has optional properties. Using Required<User> makes them all required.
Typescript
interface User {
  name?: string;
  age?: number;
}

const user1: Required<User> = {
  name: "Alice",
  age: 30
};
All properties in Config become required with Required.
Typescript
type Config = {
  url?: string;
  timeout?: number;
};

const config: Required<Config> = {
  url: "http://example.com",
  timeout: 5000
};
Sample Program

This program defines a Product with optional properties. The function printProduct requires all properties using Required. The object product1 has all properties, so it works fine.

Typescript
interface Product {
  id?: number;
  name?: string;
  price?: number;
}

function printProduct(product: Required<Product>) {
  console.log(`ID: ${product.id}`);
  console.log(`Name: ${product.name}`);
  console.log(`Price: $${product.price}`);
}

const product1: Required<Product> = {
  id: 101,
  name: "Book",
  price: 15
};

printProduct(product1);
OutputSuccess
Important Notes

If you try to pass an object missing any property to a Required type, TypeScript will show an error.

Required only changes the type, it does not add or remove properties at runtime.

Summary

Required makes all properties in a type mandatory.

It helps catch missing data errors early in development.

Use it when you want to enforce complete objects.