
In TypeScript, a tuple is a specific type of array which has the following characteristics:
- The number and order of elements are fixed and must be adhered
- The type of each element is predefined and strict
Example:
// define tuple
let myTuple: [string, number, boolean, Array<String>];
// initialize value
myTuple = ['hello', 1, true, ['a', 'b', 'c']];
Another example:
// define type
type MyTuple = [number, string, boolean];
// define function that takes a tuple as argument and returns the modified tuple
const myFunction = (arg1: MyTuple): MyTuple => {
return [arg1[0] ** 3, arg1[1].replace(' ', '-'), !arg1[2]];
};
// try it
const result = myFunction([10, 'welcome to KindaCode.com', true]);
console.log(result);
Output:
[ 1000, 'welcome-to KindaCode.com', false ]
That’s it. Further reading:
- VS Code & Javascript/TypeScript: Place Curly Braces on New Line
- TypeScript: Object with Optional Properties
- React + TypeScript: Making a Reading Progress Indicator
- TypeScript: Function with Optional and Default Parameters
- React + TypeScript: Making a Custom Context Menu
- React + TypeScript: Handling Keyboard Events
You can also check out our TypeScript category page for the latest tutorials and examples.