In TypeScript, you can declare a type as nullable by using the union type syntax or the optional property syntax. In this tutorial, we will explore both methods and provide examples to demonstrate their usage.
Using Union Type Syntax
One way to declare a type as nullable is by using the union type syntax. This involves defining a type that can be either the original type or null. For example:
interface Employee {
id: number;
name: string;
salary: number | null;
}
In this example, the salary
property is declared as a union type of number
and null
. This means that the salary
property can be either a number or null.
Using Optional Property Syntax
Another way to declare a type as nullable is by using the optional property syntax. This involves adding a question mark (?
) after the property name. For example:
interface Employee {
id: number;
name: string;
salary?: number;
}
In this example, the salary
property is declared as an optional property. This means that the salary
property can be either a number or undefined.
Using a Custom Nullable Type
You can also define a custom nullable type using the union type syntax. For example:
type Nullable<T> = T | null;
interface Employee {
id: number;
name: string;
salary: Nullable<number>;
}
In this example, we define a custom Nullable
type that takes a generic type T
and returns a union type of T
and null
. We then use this type to declare the salary
property as nullable.
Enabling Strict Null Checks
To ensure that null checks are performed correctly, you should enable the strictNullChecks
option in your tsconfig.json
file. This will help catch errors where a null value is assigned to a non-nullable property.
For example:
{
"compilerOptions": {
"strictNullChecks": true,
// other options...
}
}
By following these methods, you can declare types as nullable in TypeScript and ensure that your code is robust and error-free.