In TypeScript, tuples are a data type that allows you to express an array with a fixed number of elements, where each element may have a different data type. Tuples are useful when you want to ensure that an array has a specific structure. Here's how you can work with tuples in TypeScript:
You can declare a tuple by specifying the types of its elements within square brackets []
:
typescriptlet myTuple: [number, string, boolean];
You can initialize a tuple by providing values that match the specified types:
typescriptmyTuple = [1, "Hello", true];
Access elements using index notation:
typescriptlet num: number = myTuple[0];
let str: string = myTuple[1];
let bool: boolean = myTuple[2];
You can use destructuring to assign tuple elements to individual variables:
typescriptlet [num, str, bool] = myTuple;
You can make elements optional by appending ?
to the type:
typescriptlet myOptionalTuple: [number, string?];
myOptionalTuple = [1]; // Valid
myOptionalTuple = [1, "Hello"]; // Valid
You can use the rest syntax (...
) to capture additional elements into an array:
typescriptlet myTuple: [number, string, ...boolean[]];
myTuple = [1, "Hello", true, false, true];
Functions can return tuples as well:
typescriptfunction createTuple(): [number, string] {
return [1, "Hello"];
}
let result: [number, string] = createTuple();
You can use readonly
to create tuples that cannot be modified after initialization:
typescriptlet readonlyTuple: readonly [number, string] = [1, "Hello"];
// readonlyTuple[0] = 2; // Error: Cannot assign to '0' because it is a read-only property.
These are some basics of working with tuples in TypeScript. Keep in mind that using tuples can be beneficial for maintaining a fixed structure, but it's essential to use them judiciously based on the specific requirements of your code.