4

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[]'.

1 Answer 1

3

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, Promise<Lizard>] would be {}[] (that is, roughly, an Object[]).

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

2 Comments

Thanks Sean! Can you help me with an example of Tuple's usages. It sounds to me that tuple have the similar structure of a javascript object.
Tuples are arrays with heterogenous values - you can view [1, 'hi', someSalamander] as an object (e. g. {0: 1, 1: 'hi', 2: someSalamander}), but it is an array. That is, thingTypedAsTuple instanceof Array === true. As to how you'd use it - anywhere you want to carry around a series of things as opposed to a set of named things. Some examples include [success, error], [value, validations], and [x, y, z].

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.