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

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



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
TypeScript String trim() Method TypeScript String trim() Method
How to Extend abstract class with Generics in Typescript ? How to Extend abstract class with Generics in Typescript ?
TypeScript String codePointAt() Method TypeScript String codePointAt() Method
How to use Merge Sort with TypeScript ? How to use Merge Sort with TypeScript ?
How to Sort an Array of Objects with Null Properties in TypeScript ? How to Sort an Array of Objects with Null Properties in TypeScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16