This interface describes my answers array (IActivityAnswer[]).
export interface IActivityAnswer {
createdAt: string;
id: string;
questionId: string;
score: number;
summary: string;
title: string;
mentCount?: 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 acplish this without using type any.
This interface describes my answers array (IActivityAnswer[]).
export interface IActivityAnswer {
createdAt: string;
id: string;
questionId: string;
score: number;
summary: string;
title: string;
mentCount?: 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 acplish this without using type any.
Share Improve this question edited Sep 14, 2018 at 21:53 Jen asked Sep 14, 2018 at 15:14 JenJen 711 gold badge1 silver badge4 bronze badges 7- 1 What type would you like the array to have? How do you plan on using it? – Tom Fenech Commented Sep 14, 2018 at 15:16
- 3 If you're not going to store anything in it, why have that array anyway? – Andreas Commented Sep 14, 2018 at 15:17
- What's the sense of this question? – Jacopo Sciampi 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; mentCount?: number; } I make an api call to get data. While the api call is pending the array is empty. – Jen Commented Sep 14, 2018 at 15:37
- 1 Wele to Stack Overflow! For best results, please review the documentation on how to ask a good question and what constitutes a minimal reproducible example. – jcalz Commented Sep 14, 2018 at 15:42
2 Answers
Reset to default 9As 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.
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.