Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a TypeScript interface for an empty array?

This interface describes my answers array (IActivityAnswer[]).

export interface IActivityAnswer {
  createdAt: string;
  id: string;
  questionId: string;
  score: number;
  summary: string;
  title: string;
  commentCount?: number;
}

Some users won't have any answers (so they will have an empty array). How do I define a type for empty array. I want to accomplish this without using type any.

like image 361
Jen Avatar asked Sep 14 '18 15:09

Jen


People also ask

How would you define an empty array interface in TypeScript?

To declare an empty array for a type variable, set the array's type to Type[] , e.g. const arr: Animal[] = [] . Any elements you add to the array need to conform to the specific type, otherwise you would get an error. Copied!

How do you write an interface for an array?

To define an interface for an array of objects, define the interface for the type of each object and set the type of the array to be Type[] , e.g. const arr: Employee[] = [] . All of the objects you add to the array have to conform to the type, otherwise the type checker errors out.

How do you declare an array of objects interface in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!


2 Answers

As of TypeScript 3.0, you can use the empty tuple type, written [].

const empty: [] = [];

However, even without this feature, I don't understand why you would need to use any since you could write something like

const empty = <never[] & {length: 0}>[];

The empty tuple type [] should be preferred as it provides more robust checking and better error messages when misused.

like image 99
Aluan Haddad Avatar answered Sep 20 '22 18:09

Aluan Haddad


You can specify IActivityAnswer[] and the type would be defined as the following:

An array containing IActivityAnswer objects, or an array not containing IActivityAnswer objects, i.e. an empty array.

like image 22
Nicholas Gentile Avatar answered Sep 21 '22 18:09

Nicholas Gentile