duezz duezz - 4 months ago 30
TypeScript Question

Type 'Array[]' is not assignable to type '[Array]'

This error keeps bugging me while I'm trying to get a grab on typescript. Can anyone explain what is the difference between the two 'array'? Is any of this not an array? If not, what is it then?

[ts] Type 'AppointmentItemData[]' is not assignable to type '[AppointmentItemData]'.
Property '0' is missing in type 'AppointmentItemData[]'.


Your first type (AppointmentItemData[]) is an array of AppointmentItemData elements, while your second type is a tuple, that may only ever contain a single AppointmentItemData. Quoting from the docs:

Tuple types allow you to express an array where the type of a fixed number of elements is known, but need not be the same. For example, you may want to represent a value as a pair of a string and a number:

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error

Typescript allows you to encode that "this variable should only every have a 3 element array in it, where the first element is a number, the second is a string, and the third is a Promise that will eventually resolve to something shaped like a Lizard", whereas if it didn't the only way to encode [number, string, Lizard] would be {}[] (that is, roughly, an Object[]).