Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Tuples

TypeScript Tuples

We know that the data types of elements in an array are generally the same (arrays of type any[] can differ); if the stored elements have different data types, you need to use a tuple.

A tuple (Tuple) in TypeScript is a special type of array that allows storing elements of different types. Unlike ordinary arrays, each element in a tuple has a clear type and position. Tuples can be used in many scenarios to represent data structures with a fixed length and known element types.

The syntax for creating a tuple is as follows:

let tuple: [类型1, 类型2, 类型3, ...];

Example

Declare a tuple and initialize it:



let mytuple: [number, string];

mytuple = [42,"Runoob"];

In the example above, mytuple is a tuple containing a number-type element and a string-type element.

Accessing tuples

Elements in a tuple are accessed by index: the first element has index 0, the second 1, and so on, with the nth being n-1. The syntax is as follows:

tuple_name[index]

Example

The following example defines a tuple containing elements of two types: number and string:

TypeScript

let

mytuple

:

[

number

,

string

,

boolean

]

=

[

42

,

"

Runoob

"

,

true

]

;

//

Accessing Tuple Elements

let

num

=

mytuple

[

0

]

;

//

Access the first element, with value 42 and type number

let

str

=

mytuple

[

1

]

;

//

Access the second element, with value "Runoob" and type string

let

bool

=

mytuple

[

2

]

;

//

Access the third element, with value true and type boolean

console

.

log

(

num

)

;

//

Output: 42

console

.

log

(

str

)

;

//

Output: Runoob

console

.

log

(

bool

)

;

//

Output: true

Compile the above code to get the following JavaScript code:

JavaScript

var

mytuple

=

[

42

,

"

Runoob

"

,

true

]

;

//

Accessing Tuple Elements

var

num

=

mytuple

[

0

]

;

//

Access the first element, with value 42 and type number

var

str

=

mytuple

[

1

]

;

//

Access the second element, with value "Runoob" and type string

var

bool

=

mytuple

[

2

]

;

//

Access the third element, with value true and type boolean

console

.

log

(

num

)

;

//

Output: 42

console

.

log

(

str

)

;

//

Output: Runoob

console

.

log

(

bool

)

;

//

Output: true

The output is:

42

Runoob

true


Tuple Operations

We can use the following two functions to add new elements to or remove elements from a tuple:

The push method can add an element to the end of a tuple; the type must conform to the type constraints defined in the tuple. If it exceeds the tuple's type constraints, TypeScript will report an error.

TypeScript

var

tuple

=

[

42

,

"

Hello

"

]

;

//

Add an element that matches the type

tuple

.

push

(

"

World

"

)

;

//

Valid, because the tuple defines an optional string type

console

.

log

(

tuple

)

;

//

Output: [42, "Hello", "World"]

Compile the above code to get the following JavaScript code:

JavaScript

var

tuple

=

[

42

,

"

Hello

"

]

;

//

Add an element that matches the type

tuple

.

push

(

"

World

"

)

;

//

Valid, because the tuple defines an optional string type

console

.

log

(

tuple

)

;

//

Output: [42, "Hello", "World"]

The output is:

[ 42, 'Hello', 'World' ]

The pop method removes an element from the end of a tuple and returns it. The type of the returned element is inferred from the tuple's defined types.

Example

let tuple

:

[

number

,

string

,

boolean

]

=

[

42

,

"Hello"

,

true

]

;

// Remove the last element

let lastElement

=

tuple.

pop

(

)

;

console.

log

(

lastElement

)

;

// Output: true

console.

log

(

tuple

)

;

     

// Output: [42, "Hello"]


Updating Tuples

Tuples are mutable, which means we can perform update operations on them:

TypeScript

var

mytuple

=

[

42

,

"

Runoob

"

,

"

Taobao

"

,

"

Google

"

]

;

//

Create a tuple

console

.

log

(

"

The first element of the tuple is:

"

mytuple

[

0

]

)

//

Update a tuple element

mytuple

[

0

]

=

121

console

.

log

(

"

The first element in the tuple is updated to:

"

mytuple

[

0

]

)

Compile the above code to get the following JavaScript code:

JavaScript

var

mytuple

=

[

42

,

"

Runoob

"

,

"

Taobao

"

,

"

Google

"

]

;

//

Create a tuple

console

.

log

(

"

The first element of the tuple is:

"

mytuple

[

0

]

)

;

//

Update a tuple element

mytuple

[

0

]

=

121

;

console

.

log

(

"

The first element in the tuple is updated to:

"

mytuple

[

0

]

)

;

The output is:

元组的第一个元素为:42

元组中的第一个元素更新为:121


Destructuring Tuples

We can also assign tuple elements to variables, as shown below:

TypeScript

let

a

:

[

number

,

string

,

boolean

]

=

[

42

,

"

Hello

"

,

true

]

;

//

Create a tuple

var

[

b

,

c

]

=

a

console

.

log

(

b

)

console

.

log

(

c

)

Compile the above code to get the following JavaScript code:

JavaScript

var

a

=

[

42

,

"

Hello

"

,

true

]

;

//

Create a tuple

var

b

=

a

[

0

]

,

c

=

a

[

1

]

;

console

.

log

(

b

)

;

console

.

log

(

c

)

;

The output is:

42

Hello


Using Labeled Tuples

TypeScript also allows adding a label to each element in a tuple, making the tuple's meaning clearer:



let tuple: [id: number, name: string] = [1, "John"];

In this example, id and name are the tuple's labels, making the code more readable.


Practical Applications of Tuples

Tuples are commonly used when a function needs to return multiple values, or to represent data with a fixed structure, such as:

Example

function

getUserInfo

(

)

:

[

number

,

string

]

{

   

return

[

1

,

"John Doe"

]

;

}

const

[

userId

,

userName

]

=

getUserInfo

(

)

;

console.

log

(

userId

)

;

 

// Output: 1

console.

log

(

userName

)

;

// Output: John Doe


Type Inference for Tuples

TypeScript can automatically infer a tuple's type from the array's elements:



let tuple = [42, "Hello"] as const; // 元组类型:[42, "Hello"]

With an as const assertion, TypeScript treats the tuple as an immutable constant tuple.


Concatenating Tuples

Tuples can be concatenated using the array concat method, but note that the result of the concatenation is an ordinary array, not a tuple.

Example

let tuple1

:

[

number

,

string

]

=

[

42

,

"Hello"

]

;

let tuple2

:

[

boolean

,

number

]

=

[

true

,

100

]

;

let result

=

tuple1.

concat

(

tuple2

)

;

// The result is an array: [42, "Hello", true, 100]

console.

log

(

result

)

;

// Output: [42, "Hello", true, 100]


Slicing Tuples

You can use the array slice method to slice a tuple, returning a new array.

Example

let tuple

:

[

number

,

string

,

boolean

]

=

[

42

,

"Hello"

,

true

]

;

let sliced

=

tuple.

slice

(

1

)

;

// Slice starting from index 1

console.

log

(

sliced

)

;

// Output: ["Hello", true]


Traverse a tuple

You can use a for...of loop or the forEach method to iterate over the elements in a tuple.

Example

let tuple

:

[

number

,

string

,

boolean

]

=

[

42

,

"Hello"

,

true

]

;

// Use a for...of loop

for

(

let item of tuple

)

{

    console.

log

(

item

)

;

}

// Use the forEach method

tuple.

forEach

(

item

=>

console.

log

(

item

)

)

;


Converting to an Ordinary Array

Although a tuple is an array with a fixed length and fixed types, you can convert it to an ordinary array using Array.prototype methods for further processing.

Example

let tuple

:

[

number

,

string

,

boolean

]

=

[

42

,

"Hello"

,

true

]

;

// Convert to an array and use array methods

let array

=

Array

.

from

(

tuple

)

;

array.

push

(

"New Element"

)

;

console.

log

(

array

)

;

// Output: [42, "Hello", true, "New Element"]


Spreading Tuples

Using the rest operator, you can easily merge multiple tuples into a new tuple:

Example

let tuple1

:

[

number

,

string

]

=

[

42

,

"Hello"

]

;

let tuple2

:

[

boolean

]

=

[

true

]

;

let extendedTuple

:

[

number

,

string

,

...

typeof

tuple2

]

=

[

42

,

"Hello"

,

...

tuple2

]

;

console.

log

(

extendedTuple

)

;

// Output: [42, "Hello", true]