TypeScript: Tuple Examples

Updated: July 29, 2022 By: Augustus Post a comment

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:

You can also check out our TypeScript category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles