NonNullable type in Typescript - Time & Space Complexity
Let's explore how the NonNullable type affects the time it takes for TypeScript to process types.
We want to see how the work grows when removing null and undefined from types.
Analyze the time complexity of the following TypeScript type operation.
type NonNullable<T> = T extends null | undefined ? never : T;
// Example usage:
type CleanType = NonNullable<string | null | undefined>;
This code removes null and undefined from a type union.
Look at what happens when TypeScript checks each part of the union.
- Primary operation: Checking each union member against null or undefined.
- How many times: Once for each member in the union type.
As the number of union members grows, TypeScript checks each one separately.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 checks |
| 10 | 10 checks |
| 100 | 100 checks |
Pattern observation: The work grows directly with the number of union members.
Time Complexity: O(n)
This means the time to process grows linearly with the number of types in the union.
[X] Wrong: "Removing null and undefined happens instantly no matter how many types there are."
[OK] Correct: Each type in the union must be checked, so more types mean more work.
Understanding how type operations scale helps you write efficient and clear TypeScript code, a skill valued in many coding tasks.
What if we used a nested union type inside NonNullable? How would that affect the time complexity?