TypeScript NonNullable Guide
October 26, 2023
TypeScript, with its static type checking, provides a way to catch certain types of errors during compile time. One of its powerful type manipulation tools is NonNullable<T>
, which filters out null
and undefined
from a given type. In this guide, we'll dive into the NonNullable
utility type and its practical uses.
Basic Understanding of NonNullable<T>
The NonNullable<T>
utility type represents a type that doesn't allow null
or undefined
.
type NonNullable<T> = T extends null | undefined ? never : T;
When applied, this type will exclude null
and undefined
from the type T
.
Example:
type MaybeString = string | null | undefined; type StringOnly = NonNullable<MaybeString>; // Result: string
Practical Usage Scenarios
Function Parameters
If you have a function that should not accept null
or undefined
values, NonNullable
can be handy.
function printValue(value: NonNullable<string | null | undefined>) { console.log(value); } printValue("Hello"); // OK printValue(null); // Error printValue(undefined); // Error
Filtering Arrays
When working with arrays that might contain nullable values, you can use NonNullable
in combination with a filter to remove them.
const items: (string | null | undefined)[] = ["apple", null, "banana", undefined, "cherry"]; const filteredItems: string[] = items.filter((item): item is NonNullable<typeof item> => item !== null && item !== undefined);
Working with Object Properties
For objects that might have optional properties, you can use NonNullable
to ensure some properties always have a value.
interface User { id: number; name?: string | null; } function getUserName(user: User): NonNullable<User['name']> { if (!user.name) { throw new Error("User has no name!"); } return user.name; }
You could ship faster.
Imagine the time you'd save if you never had to build another internal tool, write a SQL report, or manage another admin panel again. Basedash is built by internal tool builders, for internal tool builders. Our mission is to change the way developers work, so you can focus on building your product.
Gotchas and Limitations
While NonNullable
is powerful, it's essential to remember its scope:
It Doesn't Alter Runtime Behavior
Like other TypeScript features, NonNullable
only provides static type checking. It doesn't change the runtime behavior of JavaScript. Always ensure that you handle potential null or undefined values in your runtime code.
Requires Strict Null Checks
For NonNullable
to be effective, you should enable the strictNullChecks
compiler option in your tsconfig.json
. This ensures that TypeScript enforces null and undefined checks.
{ "compilerOptions": { "strictNullChecks": true } }
Not Recursive on Nested Types
If you're working with deeply nested types, NonNullable
won't recursively make all properties non-nullable. In such cases, you might need to apply NonNullable
more deeply or create custom utility types.
Alternatives to NonNullable
If NonNullable
doesn't quite fit your needs, TypeScript offers other utility types:
Required<T>
: Makes all properties ofT
required.Partial<T>
: Makes all properties ofT
optional.Readonly<T>
: Makes all properties ofT
readonly.
Dive into TypeScript's utility types to find the right tools for your needs. They can significantly enhance type safety and developer productivity in your projects.
TOC
October 26, 2023
TypeScript, with its static type checking, provides a way to catch certain types of errors during compile time. One of its powerful type manipulation tools is NonNullable<T>
, which filters out null
and undefined
from a given type. In this guide, we'll dive into the NonNullable
utility type and its practical uses.
Basic Understanding of NonNullable<T>
The NonNullable<T>
utility type represents a type that doesn't allow null
or undefined
.
type NonNullable<T> = T extends null | undefined ? never : T;
When applied, this type will exclude null
and undefined
from the type T
.
Example:
type MaybeString = string | null | undefined; type StringOnly = NonNullable<MaybeString>; // Result: string
Practical Usage Scenarios
Function Parameters
If you have a function that should not accept null
or undefined
values, NonNullable
can be handy.
function printValue(value: NonNullable<string | null | undefined>) { console.log(value); } printValue("Hello"); // OK printValue(null); // Error printValue(undefined); // Error
Filtering Arrays
When working with arrays that might contain nullable values, you can use NonNullable
in combination with a filter to remove them.
const items: (string | null | undefined)[] = ["apple", null, "banana", undefined, "cherry"]; const filteredItems: string[] = items.filter((item): item is NonNullable<typeof item> => item !== null && item !== undefined);
Working with Object Properties
For objects that might have optional properties, you can use NonNullable
to ensure some properties always have a value.
interface User { id: number; name?: string | null; } function getUserName(user: User): NonNullable<User['name']> { if (!user.name) { throw new Error("User has no name!"); } return user.name; }
You could ship faster.
Imagine the time you'd save if you never had to build another internal tool, write a SQL report, or manage another admin panel again. Basedash is built by internal tool builders, for internal tool builders. Our mission is to change the way developers work, so you can focus on building your product.
Gotchas and Limitations
While NonNullable
is powerful, it's essential to remember its scope:
It Doesn't Alter Runtime Behavior
Like other TypeScript features, NonNullable
only provides static type checking. It doesn't change the runtime behavior of JavaScript. Always ensure that you handle potential null or undefined values in your runtime code.
Requires Strict Null Checks
For NonNullable
to be effective, you should enable the strictNullChecks
compiler option in your tsconfig.json
. This ensures that TypeScript enforces null and undefined checks.
{ "compilerOptions": { "strictNullChecks": true } }
Not Recursive on Nested Types
If you're working with deeply nested types, NonNullable
won't recursively make all properties non-nullable. In such cases, you might need to apply NonNullable
more deeply or create custom utility types.
Alternatives to NonNullable
If NonNullable
doesn't quite fit your needs, TypeScript offers other utility types:
Required<T>
: Makes all properties ofT
required.Partial<T>
: Makes all properties ofT
optional.Readonly<T>
: Makes all properties ofT
readonly.
Dive into TypeScript's utility types to find the right tools for your needs. They can significantly enhance type safety and developer productivity in your projects.
October 26, 2023
TypeScript, with its static type checking, provides a way to catch certain types of errors during compile time. One of its powerful type manipulation tools is NonNullable<T>
, which filters out null
and undefined
from a given type. In this guide, we'll dive into the NonNullable
utility type and its practical uses.
Basic Understanding of NonNullable<T>
The NonNullable<T>
utility type represents a type that doesn't allow null
or undefined
.
type NonNullable<T> = T extends null | undefined ? never : T;
When applied, this type will exclude null
and undefined
from the type T
.
Example:
type MaybeString = string | null | undefined; type StringOnly = NonNullable<MaybeString>; // Result: string
Practical Usage Scenarios
Function Parameters
If you have a function that should not accept null
or undefined
values, NonNullable
can be handy.
function printValue(value: NonNullable<string | null | undefined>) { console.log(value); } printValue("Hello"); // OK printValue(null); // Error printValue(undefined); // Error
Filtering Arrays
When working with arrays that might contain nullable values, you can use NonNullable
in combination with a filter to remove them.
const items: (string | null | undefined)[] = ["apple", null, "banana", undefined, "cherry"]; const filteredItems: string[] = items.filter((item): item is NonNullable<typeof item> => item !== null && item !== undefined);
Working with Object Properties
For objects that might have optional properties, you can use NonNullable
to ensure some properties always have a value.
interface User { id: number; name?: string | null; } function getUserName(user: User): NonNullable<User['name']> { if (!user.name) { throw new Error("User has no name!"); } return user.name; }
You could ship faster.
Imagine the time you'd save if you never had to build another internal tool, write a SQL report, or manage another admin panel again. Basedash is built by internal tool builders, for internal tool builders. Our mission is to change the way developers work, so you can focus on building your product.
Gotchas and Limitations
While NonNullable
is powerful, it's essential to remember its scope:
It Doesn't Alter Runtime Behavior
Like other TypeScript features, NonNullable
only provides static type checking. It doesn't change the runtime behavior of JavaScript. Always ensure that you handle potential null or undefined values in your runtime code.
Requires Strict Null Checks
For NonNullable
to be effective, you should enable the strictNullChecks
compiler option in your tsconfig.json
. This ensures that TypeScript enforces null and undefined checks.
{ "compilerOptions": { "strictNullChecks": true } }
Not Recursive on Nested Types
If you're working with deeply nested types, NonNullable
won't recursively make all properties non-nullable. In such cases, you might need to apply NonNullable
more deeply or create custom utility types.
Alternatives to NonNullable
If NonNullable
doesn't quite fit your needs, TypeScript offers other utility types:
Required<T>
: Makes all properties ofT
required.Partial<T>
: Makes all properties ofT
optional.Readonly<T>
: Makes all properties ofT
readonly.
Dive into TypeScript's utility types to find the right tools for your needs. They can significantly enhance type safety and developer productivity in your projects.
What is Basedash?
What is Basedash?
What is Basedash?
Ship faster, worry less with Basedash
Ship faster, worry less with Basedash
You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.
You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.
You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.
Dashboards and charts
Edit data, create records, oversee how your product is running without the need to build or manage custom software.
USER CRM
ADMIN PANEL
SQL COMPOSER WITH AI
Related posts
Related posts
Related posts
How to turn webpages into editable canvases with a JavaScript bookmarklet
Kris Lachance
How to fix the "not all code paths return a value" issue in TypeScript
Kris Lachance
Working with WebSockets in Node.js using TypeScript
Kris Lachance
Type Annotations Can Only Be Used in TypeScript Files
Kris Lachance
Guide to TypeScript Recursive Type
Kris Lachance
How to Configure Knex.js with TypeScript
Kris Lachance