Back

TypeScript Required Utility Type

`Required< T >` makes all optional properties in a type mandatory, ensuring objects include all fields.

Basic Usage

type User = {
    id?: number;
    name?: string;
  };
  
  const user1: User = {};
  const user2: Required<User> = {
    id: 1,
    name: "Alice"
  };
  
  // Error: Property 'id' is missing in type '{}' but required in type 'Required<User>'.

While `User` might have optional fields, `Required< User >` makes all fields required, causing errors if some are missing.

Using as Function Parameter

interface Config {
    apiUrl?: string;
    timeout?: number;
  }
  
  function setup(config: Required<Config>) {
    console.log("API URL:", config.apiUrl);
    console.log("Timeout:", config.timeout);
  }
  
  setup({
    apiUrl: "https://api.example.com",
    timeout: 5000
  });

The `setup` function uses `Required< Config >` to guarantee all optional properties are provided.

Type Transformation Example

type PartialUser = {
    id?: number;
    name?: string;
  };
  
  type CompleteUser = Required<PartialUser>;
  
  const user: CompleteUser = {
    id: 123,
    name: "Bob"
  };
  
  console.log(user);
  // Output: { id: 123, name: "Bob" }

Transforming `PartialUser` to `Required< PartialUser >` enforces all fields, preventing missing properties.

When to Use Required?

`Required` is useful when you must ensure all data fields are present, such as validating API responses.

Back