TypeScript NonNullable<Type> Utility Type
Last Updated :
25 Oct, 2023
In this article, we are going to learn about NonNullable<Type> Utility Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, the NonNullable<Type> utility is used to create a new type by removing null and undefined from the given type. It ensures that the resulting type only contains non-null and non-undefined values.
Syntax:
type NonNullableType = NonNullable<Type>;
Where–
- NonNullableType is the name of the new type that will contain non-null and non-undefined values.
- Type is the original type from which you want to remove null and undefined.
Example 1: In this example, OriginalType is a type that can either be a string, null, or undefined.NonNullableType is created by applying the NonNullable<OriginalType> utility, which removes null and undefined from OriginalType.
Javascript
type OriginalType = string | null | undefined;
type NonNullableType = NonNullable<OriginalType>;
const value1: NonNullableType = "GeeksforGeeks" ;
console.log(value1)
|
Output:
Example 2: In this example, OriginalType is a type representing an object with a name property of type string and course property that can be a string, null, or undefined. We create a new type called NonNullableCourseType by using the NonNullable<OriginalType[“course”]> utility to remove null and undefined from the course property.
Javascript
type OriginalType = {
name: string;
course: string | null | undefined;
};
type NonNullableCourseType = {
name: string;
course: NonNullable<OriginalType[ "course" ]>;
};
const person1: NonNullableCourseType = {
name: "GeeksforGeeks" ,
course: 'Java' ,
};
console.log(person1)
|
Output:
Share your thoughts in the comments
Please Login to comment...