Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are “named or labeled tuples” in Typescript?

Reading the changes in Typescript 4.0, I found the new feature:

Labeled Tuple Elements

I thought elements could either be indexed by numbers (like in tuples and lists) or by keys (like in dicts). I don't expected they could be indexed both ways.

my questions is:

  • Why/when should I use named tuples instead of normal tuples?
like image 537
zerocewl Avatar asked Aug 28 '20 07:08

zerocewl


People also ask

What are tuples in TypeScript?

A tuple is a TypeScript type that works like an array with some special considerations: The number of elements of the array is fixed. The type of the elements is known. The type of the elements of the array need not be the same.

What is the difference between a tuple and an array in TypeScript?

The structure of the tuple needs to stay the same (a string followed by a number), whereas the array can have any combination of the two types specified (this can be extended to as many types as is required).

When should I use tuple TypeScript?

TypeScript tuples are like arrays with a fixed number of elements. They provide us with a fixed size container that can store values of multiple types, where the order and structure are very important. This data type is best used when we know exactly how many types we want to allow in an array.


1 Answers

This is purely for documentation purposes, it has no semantics. They are just a way of putting names in the type signature--they type check identically to tuples without names, and the runtime behavior is identical as well.

While these have no impact on type-checking, the lack of labels on tuple positions can make them harder to use – harder to communicate our intent.

Emphasis added.

Use them whenever you want to document what the names of elements in a tuple are in the type signature of a function that uses them.

Example

You might have a Range type, which is [start, end]:

type Range = [start: number, end: number];

Or your Range type might be [start, length]:

type Range = [start: number, length: number];

Or you could use unnamed tuples:

type Range = [number, number];

These three definitions have identical semantics as far as TypeScript is concerned. You can access the members through destructuring by array access (e.g. arr[0]), just like any other array--they are not special. You cannot access the elements by name... again, these are just ordinary JavaScript array objects.

like image 154
Dietrich Epp Avatar answered Nov 02 '22 04:11

Dietrich Epp