Open In App

How to Avoid Inferring Empty Array in TypeScript ?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, the empty arrays are inferred as never[] by default, denoting an array incapable of containing any elements. This occurs when TypeScript fails to deduce the type of array elements from the context, notably in scenarios involving spread operators, the Array constructor, or methods like Array.prototype.map.

The below methods can be used to avoid inferring empty arrays in TypeScript.

By Specifying the type explicitly

The simplest approach to circumvent this issue is by explicitly specifying the type of the array during declaration using the basic syntax of explicitly typing variables in TypeScript.

Syntax:

let empty: Array<number> = [];
let empty: number[] = [];

Example: The below code example will explain how you can explicitly type variables in TypeScript.

Javascript




let empty: number[] = [];
empty.push(5);
console.log(empty, ", ", typeof empty[0]);


Output:

[5], number

Using type assertion

Another method is to employ a type assertion, informing TypeScript about the type of values contain by the array more accurately than it can infer.

Syntax:

let empty = [] as number[]; 
let empty = <number[]>[];

Example: The below code example uses type assertion to avoid type inferring in empty arrays.

Javascript




let empty = [] as number[];
empty.push(1);
console.log(empty, ", ", typeof empty[0]);


Output:

[1], number

Using non-empty array literal

You can also use a non-empty array literal, ensuring TypeScript infers the type of array elements correctly.

Syntax:

let empty = [0];
empty.pop();

Example: The below example is a practical implementation of above-discussed approach.

Javascript




let empty = [0];
empty.push(1);
console.log(empty, ", ", typeof empty[0]);


Output:

[0, 1], number


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads