A tuple type is used to represent an array with a known number and type of elements. The types of each element need not be the same.

Define tuple types

The order of element types specified in tuples must be identical, and no more or less:

// Define a tuple type
let x: [string, number];
x = ['hello'.10]; // OK
x = [10.'hello']; // Error
Copy the code

When accessing an element with a known index, we get the correct type:

console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Property 'substr' does not exist on type 'number'
Copy the code

Tuple out of bounds:

// You can add elements out of bounds (not recommended), but not out of bounds
const list: [string, number] = ['Sherlock'.1887]
list.push('hello world')
console.log(list)      // [ 'Sherlock', 1887, 'hello world' ]
console.log(list[2])   // Tuple type '[string, number]' of length '2' has no element at index '2'
Copy the code

Optional element type

Tuple types are allowed to have a suffix on the element type. To indicate that the element is optional:

letlist: [number, string?, boolean?]  list = [10.'Sherlock'.true]
list = [10.'Sherlock']
list = [10]


Copy the code

Optional elements must come after required elements, i.e., if an element is suffixed? And all elements after that are suffixed, right? No. :

let list1: [number, string?, boolean] 
// Error: A required element cannot follow an optional element
Copy the code

application

  1. The React useState Hook
import { useState } from 'react';
const [loading, setLoading] = useState<boolean>(false); 
Copy the code
  1. Tuples are used when the data source is a file like CVS
type Touple = [string, number, string];
let csvData: Touple[] = [
    ['Joe'.18.'male'], 
    ['bill'.14.'male']].Copy the code

Rest use of tuple types

A tuple can be passed to a function as an argument, and the Rest parameter of the function can be defined as a tuple type:

declare function rest(. args: [number, string, boolean]) :void/ / equivalentdeclare function rest(arg1: number, arg2: string, arg3: boolean) :void
Copy the code

In the declaration file (.d.ts), the keyword declare indicates the declaration role. The declaration file is used to write third-party libraries, which are generated at compile time by setting declaration to true in the tsconfig.json file.

const list: [number, ...string[]] = [10.'a'.'b'.'c']
const list1: [string, ...number[]] = ['a'.1.2.3]
Copy the code

Learning links

  • www.imooc.com/wiki/typesc…
  • www.runoob.com/typescript/…