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.
// Original type with // nullable and undefined values type OriginalType = string | null | undefined;
// Applying NonNullable utility // to remove null and undefined type NonNullableType = NonNullable<OriginalType>; const value1: NonNullableType = "GeeksforGeeks" ; // Valid
console.log(value1) //const value2: NonNullableType = null; // Error: Type 'null' is not // assignable to type 'string'. //const nonNullableValue3: NonNullableType = undefined; // Error: Type 'undefined' is //not assignable to type 'string'. |
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.
// Original type with nullable and undefined values type OriginalType = { name: string;
course: string | null | undefined;
};
// Applying NonNullable utility to
// remove null and undefined from 'course'
type NonNullableCourseType = {
name: string;
course: NonNullable<OriginalType[ "course" ]>;
};
const person1: NonNullableCourseType = {
name: "GeeksforGeeks" ,
course: 'Java' ,
}; // Valid
console.log(person1)
// const person2: NonNullableCourseType = {
// name: "GeeksforGeeks",
// course: null,
// }; //Error: Type 'null' is
// not assignable to type 'string'.
// const person3: NonNullableCourseType = {
// name: "GeeksforGeeks",
// course: undefined,
// }; //Error: Type 'undefined' is not
//assignable to type 'string'.
|
Output: