Typescript nullable type with examples


In this tutorial, We are going to discuss about following things with examples

  • How to define type that can be string or null?
  • How to assign null to variable?
  • typescript nullable return type
  • How to assign interface with null type

In typescript applications, dealing with nullable types is important step for avoid runtime problems.

How to declare assign nullable types with strictNullCheck in typescript?

Typescript is static typed version of javascript, So strictNullCheck configuration in tsconfig.json allows to avoid nullable errors.

strictNullCheck=false - null and undefined are sub types of existing type, so we can assign to them with out error.

Declared a string variable and can be assigned with string,null and undefined.

let name: string;
name = "johan";  // valid
name = null;      // valid
name = undefined; // valid

if strictNullCheck is set to true, then the null and undefined values are not assigned to properties of different type.

let name: string;
name = "johan";  // valid
name = null;      // error
name = undefined; // error

In this case, null and undefined are treated as a separate type which are not assigned to properties of different type.

Fix is to add union type for variable declaration.

let name: string | null| undefined;
name = "Something";  // valid
name = null;      // valid
name = undefined; // valid

How to allow null type parameter in a function in typescript?

In this example, How functional parameters allow null values with different approaches.

Let’s declare an function in typescript with a string parameter.

function printName(name: string) {
    console.info(name);
}

This function accepts string only, null, undefined and empty is not allowed.

printName("Franck"); // valid
printName(null); // error not valid
printName(undefined); // error not valid
printName() // // error not valid

Let’s add union type null to function parameter to allow null values

function printName(name: string|null) {
    console.info(name);
}

This function allows string and null types and other types are not allowed.

printName("Franck"); // valid
printName(null); // valid
printName(undefined); // error not valid
printName() // // error not valid

Now let’s add optional ? to functional parameter. This allows to accepts optional parameter or undefined and string only.

Below function adds optional parameter

function printName(name?: string) {
    console.info(name);
}

This function allows string or optional name or undefined types and other types are not allowed.

printName("Franck"); // valid
printName(null); // error invalid
printName(undefined); // valid
printName() // valid

To allow null and undefined and optional parameters, We can pass union with optional parameter

function printName(name?: string|null) {
    console.info(name);
}

This allows all cases seen below

printName("Franck"); // valid
printName(null); // valid
printName(undefined); // valid
printName() // valid

How to return nullable type in typescript?

export class Employee {

    private name: string;

    public constructor() {

    }

    public getName(name: string) {

        return null;
    }
}

if name is null, It throws an error,

To avoid this, you have to declare as follows

public name: string | null;

if name is not an string, It return null.

How to assign null to an interface?

let’s declare an interface with simple field name

interface employee {
    name: any;
}

let’s see what is the behaviour when an interface is assigned with null

  • strictNullCheck=false in tsconfig.json

    It is very easy to add null value to an interface

    let emp:employee = null; 
    
  • strictNullCheck=true in tsconfig.json

with enabling this , assign null to an interface throws an error Type ‘null’ is not assignable to type ‘employee’.(2322)

let emp:employee = null; 

The solution is to add union type with null

let emp:employee| null= null; 

How to declare interface field as nullable in typescript

An interface can have properties of different types, Lets add how to add nullable types to this properties in typescript.

Let’s declare interface with few more properties

interface Employee {
    name: string;
    department: string;
}

declare an objects of above interface and assign data. The below works and not thrown an error

var emp1: Employee = { name: 'Franc', department:'sales' }; // OK

Initialize an Employee object with out department field

var emp2: Employee = { name: 'Franc' }; // an compilation error 

And an error thrown below.

Property ‘department’ is missing in type ‘{ name: string; }’ but required in type ‘Employee’.(2741)

Let’s pass department with undefined

var emp3: Employee = { name: 'Franc', department: undefined }; // an compilation error

An throws an compilation error

Type ‘undefined’ is not assignable to type ‘string’.(2322)

Let’s pass department with undefined and name is null

var emp4: Employee = { name: null, department: undefined }; // an compilation error

And it throws below error Type ‘null’ is not assignable to type ‘string’.(2322)

SO, what is the solution to add null and undefined to types

An interface can be modified to add union and optional types to fields

interface Employee {
    name?: string |null;
    department?: string|null;
}

This will accepts null and undefined as well as optional values

Conclusion

In typescript, handling null is required to know to avoid runtime errors. Different approaches are documented with examples

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.