
Array, Tuple, Union in TypeScript
Array:
Array use of variables to store values. Array types can be written in one of two ways. In the first, you use the type of the elements followed by [] to denote an array of that element type.
Declaring and Initializing Arrays
To declare an initialize an array in Typescript uses the following syntax:
let arrayName:datatype[] //declaration
arrayName=[1,2,3] //initialization
many way array declaration
Tuple:
We know that an array holds multiple values of the same datatype. But sometimes, we may need to store a collection of values of different data types in a single variable. Arrays will not provide this feature, but TypeScript has datatype called tuple to achieve this purpose.
We may want to represent a value as a pair of a string and a number:
Declare a tuple type
Initialize it
Initialize it incorrectly
Accessing an element outside the set of known indices fails with an error:
Destructuring a Tuple
Union:
we can define a variable that can have multiple types of values. Two or more data types are combined using the pipe symbol (|) to denote a Union Type. In other words, a union type is written as a sequence of types separated by vertical bars.
Example: Union Type Variable
Reference: https://www.typescriptlang.org/docs/handbook/basic-types.html https://www.javatpoint.com/