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
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
Contact Us