Tuples

Tuples are a method of defining a type that has a finite number of unnamed properties. Each property has an associated type. When using a tuple, each one of these properties must be provided. This can be best explained in an example, as follows:

let tupleType: [string, boolean]; 
tupleType = ["test", false]; 
tupleType = ["test"]; 

Here, we have defined a variable named tupleType, whose type is defined as an array of types, the first of which is a string, and the second of which is a boolean. We then assign a value to the variable tupleType, and are using an array syntax to set the first property to the string "test", and the second property to the boolean value false. Note that on the last line of this snippet, we are attempting to assign a value to the tupleType variable that only has a string property. This last line will generate an error as follows:

error TS2322: Type '[string]' is not assignable to type '[string, boolean]'

What this error is showing us is that to use a tuple, each of the tuple's properties must be set, and that it is seen by the compiler as a type with two properties.

Tuples are generally used when we need to temporarily associate two normally unrelated properties.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.161.222