What are Utility Types in TypeScript?
Utility types in TypeScript are predefined types that facilitate common type transformations. They help developers with type manipulation, often simplifying and reducing repetitive code. Examples of utility types include Partial
, Readonly
, Pick
, Omit
, Record
, and NonNullable
among others.
Using the NonNullable
Utility Type
The NonNullable
utility type is used to exclude null
and undefined
from a type. It takes a type T
and returns a type that does not include null
or undefined
.
Syntax
NonNullable<T>
Example
Consider a function that processes a user object. We want to ensure that certain fields are not null or undefined.
type User = { name: string | null; age: number | undefined; }; function processUser(user: NonNullable<User>) { console.log(`User's name is ${user.name} and age is ${user.age}`); } // Correct usage processUser({ name: 'Alice', age: 30 }); // User's name is Alice and age is 30 // Incorrect usage // processUser({ name: null, age: 30 }); // Error: 'null' is not assignable to type 'string'. // processUser({ name: 'Alice', age: undefined }); // Error: 'undefined' is not assignable to type 'number'.
In this example, NonNullable<User>
ensures that both name
and age
are neither null
nor undefined
, enforcing stricter type safety when processing user data.
Conclusion
The NonNullable
utility type is particularly useful in scenarios where you want to enforce the presence of a valid value, effectively avoiding runtime errors related to null
or undefined
values.