Typescript nullable type with examples
- Admin
- Mar 6, 2024
- Typescript
In this tutorial, we will discuss the following topics with examples:
- How to define a type that can be a string or null?
- How to assign null to a variable?
- TypeScript nullable return type
- How to assign an interface with a null type In TypeScript applications, dealing with nullable types is an essential step to avoid runtime problems.
You can check other post on Fix for Object is possibly null
How to Declare Nullable Types with strictNullCheck in TypeScript?
TypeScript, being a statically typed version of JavaScript, utilizes the strictNullCheck configuration in tsconfig.json to prevent nullable errors.
When strictNullCheck
is set to false
, null
and undefined
are considered subtypes of existing types, allowing assignment without error.
For instance, consider declaring a string variable that can be assigned string, null, or undefined.
let name: string;
name = "johan"; // valid
name = null; // valid
name = undefined; // valid
However, with strictNullCheck
set to true
, assigning null
and undefined
to properties of a different type results in errors.
let name: string;
name = "johan"; // valid
name = null; // error
name = undefined; // error
In this scenario, null
and undefined
are treated as separate types and cannot be assigned to properties of a different type.
The solution is to declare a union type for the variable, encompassing all possible types:
let name: string | null | undefined;
name = "Something"; // valid
name = null; // valid
name = undefined; // valid
How to Allow a Null Type Parameter in a Function in TypeScript?
In this example, we’ll explore how functional parameters can allow null values using various approaches.
Let’s start by declaring a function in TypeScript with a string parameter:
function printName(name: string) {
console.info(name);
}
This function only accepts strings; null
, undefined
, and empty
values are not permitted.
printName("Franck"); // valid
printName(null); // error, not valid
printName(undefined); // error, not valid
printName(); // error, not valid
Next, let’s enhance the function by adding a union
type null
to the parameter, enabling acceptance of null values.
function printName(name: string | null) {
console.info(name);
}
Now, the function allows string and null types, while other types remain invalid:
printName("Franck"); // valid
printName(null); // valid
printName(undefined); // error not valid
printName(); // // error not valid
Moving on, let’s introduce an optional ?
to the functional parameter, permitting optional or undefined strings only.
The below function adds an optional parameter.
function printName(name?: string) {
console.info(name);
}
This version of the function allows strings, optional names, or undefined types, while other types are still invalid.
printName("Franck"); // valid
printName(null); // error invalid
printName(undefined); // valid
printName(); // valid
To accommodate null, undefined, and optional parameters, we can combine union with optional parameters.
function printName(name?: string | null) {
console.info(name);
}
It allows all cases as seen below.
printName("Franck"); // valid
printName(null); // valid
printName(undefined); // valid
printName(); // valid
How to Return a Nullable Type in TypeScript?
To return a nullable type in TypeScript, you can declare the type of the variable to include null as one of its possible values. Here’s how you can do it.
export class Employee {
private name: string;
public constructor() {}
public getName(name: string) {
return null;
}
}
In the above the property declared as string, that means return string, if the name is null, throws an error
To avoid this, you have to declare as follows.
public name: string | null;
if a name is not a string, It returns null.
This approach ensures that if the name is null, the function does not throw an error. Instead, it returns null as expected.
How to Assign Null to an Interface
Let’s start by declaring an interface with a simple field, name
.
interface employee {
name: any;
}
Now, let’s explore the behavior when assigning null to this interface under different TypeScript configurations.
When
strictNullCheck
is set to false in tsconfig.jsonIt’s straightforward to add a null value to an interface.
let emp: employee = null;
When
strictNullCheck
is set to true in tsconfig.json
Enabling this setting leads to an error when assigning null to an interface. Type ‘null’ is not assignable to type ‘employee’.(2322)
let emp: employee = null;
The solution is to include the union
type with null
.
let emp: employee | null = null;
How to Declare Interface Field as Nullable in TypeScript
Interfaces in TypeScript can have properties of various types, including nullable types.
Let’s demonstrate how to add nullable types to interface properties.
Consider an interface with additional properties.
interface Employee {
name: string;
department: string;
}
declare an object of the above interface and assign data. The below works and does not throw an error.
var emp1: Employee = { name: "Franc", department: "sales" }; // OK
Attempting to initialize an Employee object without the department field results in a compilation error:
var emp2: Employee = { name: "Franc" }; // an compilation error
Passing undefined as the department field also triggers a compilation error:
Property 'department' is missing in type '{ name: string; }' but required in type 'Employee'.(2741)
Let’s pass the department with undefined
var emp3: Employee = { name: "Franc", department: undefined }; // an compilation error
A throws a compilation error.
Type ‘undefined’ is not assignable to type ‘string’.(2322)
Likewise, attempting to assign null
to the name field results in an error:
var emp4: Employee = { name: null, department: undefined }; // an compilation error
And it throws the below error. Type ‘null’ is not assignable to type ‘string’.(2322)
Solution is to add Union
and Optional
Types to Fields To accommodate null
and undefined
values, modify the interface to include union and optional types.
An interface
can be modified to add union
and optional
types to fields.
interface Employee {
name?: string | null;
department?: string | null;
}
This modification allows for null, undefined, and optional values.
Conclusion
In conclusion, understanding how to handle null values in TypeScript interfaces is crucial for avoiding runtime errors. We’ve explored different approaches with examples to demonstrate these concepts effectively.