In TypeScript, a tuple is a special type of array where each element can have a specific, predetermined type. Tuples allow you to represent a fixed number of elements having different types, but the types are known at compile time.
To declare a tuple type in TypeScript, you can use the following syntax:
type TupleName = [type1, type2, ..., typeN];
For example, if you wanted to define a tuple representing a point in 3D space, you could define a tuple type ‘Point3D‘ as follows:
type Point3D = [number, number, number];
To use a tuple type, you can create a variable of the tuple type and assign values to its elements based on the specified order of types in the definition:
let point: Point3D = [1, 2, 3];
You may access the elements of tuple using its index, just like you do with a regular array:
let x = point[0]; // x will have the value 1
let y = point[1]; // y will have the value 2
let z = point[2]; // z will have the value 3
Here’s a TypeScript function example that calculates the Euclidean distance between two ‘Point3D‘ tuples:
type Point3D = [number, number, number];
function euclideanDistance(a: Point3D, b: Point3D): number {
let dx = a[0] - b[0];
let dy = a[1] - b[1];
let dz = a[2] - b[2];
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
let pointA: Point3D = [1, 2, 3];
let pointB: Point3D = [4, 5, 6];
let distance = euclideanDistance(pointA, pointB);
In this example, ‘euclideanDistance‘ is a function that takes two ‘Point3D‘ tuples and returns a ‘number‘. The distance between the two points is calculated using the Euclidean distance formula:
$$\text{distance} = \sqrt{(x\_1 - x\_2)\^2 + (y\_1 - y\_2)\^2 + (z\_1 - z\_2)\^2}.$$