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.
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!
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.
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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With