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