33. What are utility types in TypeScript, and how can you use the `NonNullable` utility type with an example?

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.

Struggling to find common date to meet with your friends? Try our new tool commondate.xyz
devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.

Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz