What are “named or labeled tuples” in Typescript?
Asked Answered
T

1

30

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?
Triplet answered 28/8, 2020 at 7:26 Comment(1)
They can't be "indexed both ways", the name labels are metadata. The actual value at runtime is still just an array, TS only exists at compile time.Pekan
D
49

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.

Digest answered 28/8, 2020 at 7:29 Comment(4)
They do have some impact on type checking if you spread them, though. Using [x?: number] as the arguments of a function will make the first param optional, whereas using [number | undefined] will not.Conviction
@m93a, you have to use the right syntax. If you want an optional entry in an unlabeled tuple, you do [number?].Argufy
How do I access the name of an element of such a tuple?Bobker
@sayandcode: You cannot access the name.Digest

© 2022 - 2024 — McMap. All rights reserved.