6

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.

7
  • 1
    What type would you like the array to have? How do you plan on using it? Commented Sep 14, 2018 at 15:16
  • 3
    If you're not going to store anything in it, why have that array anyway? Commented Sep 14, 2018 at 15:17
  • What's the sense of this question? Commented Sep 14, 2018 at 15:23
  • @TomFenech This interface describes the populated array: export interface IActivityAnswer { createdAt: string; id: string; questionId: string; score: number; summary: string; title: string; commentCount?: number; } I make an api call to get data. While the api call is pending the array is empty. Commented Sep 14, 2018 at 15:37
  • 1
    Welcome to Stack Overflow! For best results, please review the documentation on how to ask a good question and what constitutes a minimal reproducible example. Commented Sep 14, 2018 at 15:42

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Any thoughts on the case where the array is both defined with a type interface, but sometimes there will be no items in the array?
Your second declaration throws Type 'undefined[]' is not assignable to type 'never[]'.
@PatrickRoberts sorry, I forgot that strict type checking would disallow the assignment from the literal []. A type assertion is required. I've updated the answer accordingly.
another format is: const answerArray : Array<IActivityAnswer> = [ ];
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.