How to use non-empty array literal In Typescript

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


How to Avoid Inferring Empty Array in TypeScript ?

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.

Table of Content

  • By Specifying the type explicitly
  • Using type assertion
  • Using non-empty array literal

Similar Reads

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....

Using type assertion

...

Using non-empty array literal

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....

Contact Us