

{"id":112720,"date":"2023-04-10T09:00:16","date_gmt":"2023-04-10T03:30:16","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=112720"},"modified":"2023-04-10T14:29:26","modified_gmt":"2023-04-10T08:59:26","slug":"tuples-in-typescript","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/","title":{"rendered":"Tuples in TypeScript"},"content":{"rendered":"<p>TypeScript is a statically-typed programming language that builds on top of JavaScript by adding optional static typing, classes, interfaces, and other features. One of the features introduced by TypeScript is the concept of Tuples.<\/p>\n<p>A tuple is an ordered list of elements, where each element may have a different type. Tuples in TypeScript are similar to arrays, but the types of the elements in a tuple are fixed and cannot be changed once the tuple is defined.<\/p>\n<p>Using tuples can help catch errors at compile-time by enforcing the correct order and types of elements in a list. Tuples can also be used to define the return type of a function or the type of a variable that holds a fixed set of values.<\/p>\n<p>In TypeScript, you can define a tuple using square brackets, where a comma separates each element. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let DataFlair_myTuple: [string, number];\r\nDataFlair_myTuple = ['hello', 123];\r\n<\/pre>\n<p>In this example, we have defined a tuple with two elements: a string and a number. We have assigned the tuple a value of &#8220;hello&#8221; and 123.<\/p>\n<p>Tuples can also be used as return types for functions. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">function DataFlair_getPerson(): [string, number] {\r\n return ['John', 30];\r\n}\r\n\r\nlet person: [string, number] = DataFlair_getPerson();\r\nconsole.log(person[0]); \/\/ output: John\r\nconsole.log(person[1]); \/\/ output: 30\r\n<\/pre>\n<p>In this example, we have defined a function called DataFlair_getPerson that returns a tuple with two elements: a string and a number. We have then assigned the returned tuple to a variable called person and used array indexing to access the individual elements.<\/p>\n<p>Tuples can also be used with optional and rest elements. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let DataFlair_myTuple: [string, number, boolean?];\r\nDataFlair_myTuple = ['hello', 123];\r\nlet [a, b, c] = DataFlair_myTuple;\r\nconsole.log(a); \/\/ output: hello\r\nconsole.log(b); \/\/ output: 123\r\nconsole.log(c); \/\/ output: undefined\r\n<\/pre>\n<p>In this example, we have defined a tuple with three elements; the third element is optional. We have assigned the tuple a value of &#8220;hello&#8221; and 123 but have not provided a value for the optional element. We have then used destructuring to assign the individual elements to variables.<\/p>\n<p>Tuples can also be used with rest elements. Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let DataFlair_myTuple: [string, number, ...boolean[]];\r\nDataFlair_myTuple = ['hello', 123, true, false];\r\nconsole.log(DataFlair_myTuple[2]); \/\/ output: true\r\nconsole.log(DataFlair_myTuple[3]); \/\/ output: false\r\n<\/pre>\n<p>In this example, we have defined a tuple with two mandatory elements (a string and a number) and a rest element, an array of booleans. We have assigned the tuple a value of &#8220;hello,&#8221; 123, true, and false.<\/p>\n<h3>Readonly Tupple<\/h3>\n<p>In TypeScript, a readonly tuple is a tuple whose elements cannot be modified after creation.<\/p>\n<p>To define a readonly tuple, the readonly keyword can be used before the tuple type annotation:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let DataFlair_person: readonly [string, number] = ['John Doe', 30];\r\n<\/pre>\n<p>Once a readonly tuple has been defined, its elements cannot be modified directly or through any method or operation. For example, attempting to modify the elements of the DataFlair_person tuple defined above will result in a TypeScript error:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">DataFlair_person[0] = 'Jane Doe';\r\n<\/pre>\n<p>Using readonly tuples can help ensure that the data in a tuple remains immutable, preventing unintended modifications and improving the stability and reliability of a program.<\/p>\n<h3>Destructuring Tupple<\/h3>\n<p>This is a feature that allows you to extract individual elements from a data structure, such as an array or a tuple, and assign them to separate variables.<\/p>\n<p>Destructuring a tuple involves specifying variable names inside square brackets that match the order and number of elements in the tuple. For example, consider the following tuple:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let DataFlair_person: [string, number] = ['John Doe', 30];\r\n<\/pre>\n<p>We can use destructuring to extract the individual elements of the tuple and assign them to separate variables as follows:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let [name, age] = DataFlair_person;\r\n<\/pre>\n<p>In this example, the variable&#8217;s name and age are assigned the first and second elements of the DataFlair_person tuple, respectively.<\/p>\n<p>Destructuring can also be used to extract only certain elements of a tuple and skip over certain elements. For example, consider the following tuple with three elements:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let DataFlair_person: [string, number, string] = ['John Doe', 30, 'male'];\r\n<\/pre>\n<p>To extract only the first and third elements of this tuple and assign them to separate variables, we can use destructuring with commas to skip over the second element:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">let [name, , gender] = DataFlair_person;\r\n<\/pre>\n<p>In this example, the variable&#8217;s name and gender are assigned the first and third elements of the DataFlair_person tuple. The second element (the person&#8217;s age) is skipped over using a comma in the destructuring assignment.<\/p>\n<p>Destructuring tuples can help simplify code by allowing you to extract and work with individual elements of a tuple without accessing them through their index positions.<\/p>\n<h3>Tuple Methods<\/h3>\n<p>In TypeScript, tuple methods are functions that operate on tuples. Since tuples are a type of ordered list, tuple methods are similar to array methods in JavaScript but with some differences due to the fixed nature of tuples.<\/p>\n<p>Some common tuple methods in TypeScript include:<\/p>\n<p><strong>1. concat():<\/strong> Returns a new tuple that combines the elements of two or more tuples.<\/p>\n<p>For Example<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var DataFlair_employee: [number, string] = [1, 'Steve'];\r\n\r\nDataFlair_employee[1] = DataFlair_employee[1].concat(' Jobs');\r\nconsole.log(DataFlair_employee);<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">[1, &#8216;Steve Jobs&#8217;]<\/div>\n<p><strong>2. slice():<\/strong> Returns a new tuple that contains a subset of the elements of the original tuple.<\/p>\n<p><strong>For Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var DataFlair_tup = [11, 89, 23, 7, 98];\r\nvar val = DataFlair_tup.slice(2, 4);\r\nconsole.log(val);<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">[23, 7]<\/div>\n<p><strong>3. push():<\/strong> Adds one or more elements to the end of a tuple and returns the new length of the tuple.<\/p>\n<p><strong>For Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var DataFlair_tup = [11, 89, 23, 7, 98];\r\nvar val = DataFlair_tup.push(4);\r\nconsole.log(val, DataFlair_tup);<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">[11, 89, 23, 7, 98, 4]<\/div>\n<p><strong>4. pop():<\/strong> Removes the last element of a tuple and returns it.<\/p>\n<p><strong>For Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var DataFlair_tup = [11, 89, 23, 7, 98];\r\nvar val = DataFlair_tup.pop();\r\nconsole.log(DataFlair_tup);<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">[11, 89, 23, 7]<\/div>\n<p><strong>5. indexOf():<\/strong> Returns the index of the first occurrence of a specified element in a tuple or -1 if the element is not found.<\/p>\n<p><strong>For Example<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">var DataFlair_tup = [11, 89, 23, 7, 98];\r\nconsole.log(DataFlair_tup.indexOf(23));<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">2<\/div>\n<h3>Conclusion<\/h3>\n<p>Tuples can be a powerful tool in TypeScript for enforcing a specific data structure or ensuring a particular order of elements in an array. Tuples have a defined amount of elements. Each element has to be a specified type, making them less flexible than standard arrays.<\/p>\n<p>In conclusion, Tuples are a unique feature of TypeScript that allows you to define an array with a fixed number of elements, where each element can be different. They can represent a specific data structure or enforce a specific order of elements in an array. While they may be less flexible than regular arrays, they can be a powerful tool in TypeScript.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>TypeScript is a statically-typed programming language that builds on top of JavaScript by adding optional static typing, classes, interfaces, and other features. One of the features introduced by TypeScript is the concept of Tuples.&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":112997,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27319],"tags":[27351],"class_list":["post-112720","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-typescript-tutorials","tag-tuples-in-typescript"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Tuples in TypeScript - DataFlair<\/title>\n<meta name=\"description\" content=\"A tuple is an ordered list of elements, where each element may have a different type. Learn about typescript tuples &amp; methods with examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Tuples in TypeScript - DataFlair\" \/>\n<meta property=\"og:description\" content=\"A tuple is an ordered list of elements, where each element may have a different type. Learn about typescript tuples &amp; methods with examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-04-10T03:30:16+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-04-10T08:59:26+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-tuples.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Tuples in TypeScript - DataFlair","description":"A tuple is an ordered list of elements, where each element may have a different type. Learn about typescript tuples & methods with examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/","og_locale":"en_US","og_type":"article","og_title":"Tuples in TypeScript - DataFlair","og_description":"A tuple is an ordered list of elements, where each element may have a different type. Learn about typescript tuples & methods with examples.","og_url":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-04-10T03:30:16+00:00","article_modified_time":"2023-04-10T08:59:26+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-tuples.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Tuples in TypeScript","datePublished":"2023-04-10T03:30:16+00:00","dateModified":"2023-04-10T08:59:26+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/"},"wordCount":915,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-tuples.webp","keywords":["Tuples in TypeScript"],"articleSection":["TypeScript Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/","url":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/","name":"Tuples in TypeScript - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-tuples.webp","datePublished":"2023-04-10T03:30:16+00:00","dateModified":"2023-04-10T08:59:26+00:00","description":"A tuple is an ordered list of elements, where each element may have a different type. Learn about typescript tuples & methods with examples.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-tuples.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/typescript-tuples.webp","width":1200,"height":628,"caption":"typescript tuples"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/tuples-in-typescript\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"TypeScript Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/typescript-tutorials\/"},{"@type":"ListItem","position":3,"name":"Tuples in TypeScript"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/112720","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=112720"}],"version-history":[{"count":10,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/112720\/revisions"}],"predecessor-version":[{"id":114032,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/112720\/revisions\/114032"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/112997"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=112720"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=112720"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=112720"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}