Typescript Required<Type> Utility Type (original) (raw)

Last Updated : 03 Sep, 2024

**TypeScript's Required utility type creates a new type by making all properties of an existing type mandatory. It removes optionality from each property, ensuring that all fields must be provided, which enhances type safety and reduces potential errors in type definitions.

**Syntax

type Required = { [Property in keyof Type]-?: Type[Property]; };

Where -

**Approach: Let us see how we can use the Required step-by-step:

**Step 1: Define a new interface or type that includes some optional properties:

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

**Step 2: Define a new type that uses the Required utility type to make all properties of the Person interface required:

type RequiredPerson = Required;

**Step 3: Now, RequiredPerson is a new type that includes all properties of the Person interface, but with the ? optional modifier removed. This means that all properties of RequiredPerson are now mandatory:

const person: RequiredPerson = { name: 'John', age: 30, address: '123 Main St.', }; // This is valid

const invalidPerson: RequiredPerson = { name: 'Jane', }; // This is invalid because age and address are missing

**Step 4: Now, when all the properties are mandatory, we can use them for our requirements.

**Example 1: In this example, we convert an interface with optional properties to a required one. Using Required, we make all properties in the Person interface mandatory, including age and address.

JavaScript `

// Define a "Person" type with optional properties type Person = { name: string; age?: number; address?: string; };

// Create "RequiredPerson" type with all required properties type RequiredPerson = Required;

// Create a "RequiredPerson" instance with all properties const person: RequiredPerson = { name: "John Doe", age: 30, address: "123 Main St", };

console.log(person);

`

**Output:

{ name: 'John Doe', age: 30, address: '123 Main St' }

**Example 2: In this example, we define AddProps with num1 and optional num2. Using Required, the addNumbers function requires all properties, ensuring both num1 and num2 are provided, yielding the desired result.

JavaScript ``

// Define "AddProps" type with optional num2 type AddProps = { num1: number; num2?: number; };

// Function accepts all required properties of AddProps function addNumbers(props: Required) { const { num1, num2 } = props;

// Return the sum of num1 and num2
return num1 + num2;

}

// Call addNumbers with all required properties const result1 = addNumbers({ num1: 5, num2: 10 });

console.log(result1);

``

**Output:

15

**Conclusion: In this article, we have seen what is Required and its syntax. Since it can be used to create new types with all properties required. By using the Required type, you can ensure that all required properties are present and avoid unexpected runtime errors.