Today, we are going to explore one hidden gem of the typescript. In some cases, properties of the type can be optional.
As in,
Type Props {
a?: number;
b?: string;
}
const obj: Props = { a: 5 };
const obj2: Required = { a: 5, b: 2 };
Here, for obj2, all the properties are mandatory when we add Required. If we fail to do so, we get the below error
Property 'b' is missing in type '{ a: number; }' but required in type 'Required'.
In the real time, the best example I could think of is:
Let's say you have a TypeScript interface called Book representing a book object.
The Book interface has some optional properties, but you want to create a function that accepts only books with all the properties being required. You can use Required to achieve this:
interface Book {
title?: string;
author?: string;
genre?: string;
}
function processBook(book: Required) {
// Process the book object
}
// Usage
const book1: Book = {
title: "The Catcher in the Rye",
author: "J.D. Salinger"
};
const book2: Required = {
title: "To Kill a Mockingbird",
author: "Harper Lee",
genre: "Fiction"
};
processBook(book1); // Compilation error: Missing required properties
processBook(book2); // Valid, as all the properties are required
In this example, we have the Book interface representing a book object. The properties title, author, and genre are all optional as denoted by the ? symbol. We then define a function called processBook that accepts a book object with all the properties being required.
When we try to pass book1 to processBook, TypeScript raises a compilation error because book1 is of type Book, and it might be missing some required properties. However, book2 is explicitly declared as Required, providing all the required properties, and thus it is a valid argument for the processBook function.
Top comments (0)