How the TypeScript NonNullable Type Works
π£ Sponsor
The NonNullable
is a utility type in TypeScript which creates a new type, whilst removing all null
or undefined
elements. It lets us take existing types, and modify them so they are more suitable in certain situations. Letβs look at how it works.
Custom Types
This article covers custom types. To learn more about custom types, read my guide about it here.
NonNullable Utility Type
The NonNullable
type utility type works a lot like other utility types, in that it can take an existing type, and modify it as you see fit. As an example, letβs say we have a specific union type which accepts null
and undefined
as potential options:
type myType = string | number | null | undefined
This example works great in one example, but there is another part of our code where we donβt want to accept null
or undefined
. We could create a new type for that, or we could reuse myType
, using NonNullable
:
type myType = string | number | null | undefined
type noNulls = NonNullable<myType>
In the above example, noNulls
is now of type string | number
.
More Tips and Tricks for Typescript
- How the TypeScript ReturnType Type works
- How TypeScript Default Parameters Work
- How keyof works in Typescript
- How the typeof Operator works in TypeScript
- How the TypeScript Partial Type Works
- How Template Literal Types work in TypeScript
- TypeScript Array Type
- How Typescript Enums Work
- How the TypeScript Required Type Works
- How to setup a new Project in Typescript