Open In App

How to declare nullable type in TypeScript ?

Last Updated : 15 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In vanilla JavaScript, there are two primary data types: null and undefined. While TypeScript previously did not allow explicit naming of these types, you can now use them regardless of the type-checking mode.

To assign undefined to any property, you need to turn off the –strictNullChecks flag. However, with this flag enabled, you cannot assign undefined to members that do not have the nullable operator.

This update in TypeScript enhances type safety, allowing developers to explicitly handle cases where values may be absent, ultimately reducing runtime errors and improving code quality.

Example: The below example represents what happens if the –strictNullChecks flag is enabled and the following code is executed. 

javascript
interface Student {
 	name:string;
 	age:number;
}

let s: Student = {
 	name:'Ajay',
 	age:null
}

It will throw the below error:

Type 'null' is not assignable to type 'number'

This error won’t appear if we have –strictNullChecks flag turned off. The strictNullChecks flag protects from referencing nulls or undefined values in the code. It can be enabled by adding the -–strictNullChecks flag as an option to the command-line compiler or adding it to the tsconfig.json file. 

There is a difference between the Nullable type and “optional”. In “optional”, we provide some default value to the member or let it not be considered as a member. However if any member is assigned optional and then still assigned a value as “null” or “undefined”, then it will throw an error.

javascript
interface Student {
 	name:string;
 	age?:number;
}

let s: Student = {
 	name:'Ajay',
 	age:null
}


Next Article

Similar Reads