Skip to content

数组 and Tuples in TypeScript

类型数组使用元素类型 and tuples 使用 fixed-长度, 位置-输入数组.

你将学到

  • Two syntaxes for 数组类型: T[] and 数组<T>
  • 如何 tuples fix 类型 at 每个位置
  • Readonly 数组 and tuples for immutability
  • 常见数组操作 and 它们的类型 signatures

概念讲解

Array Types

An array of a specific element type is written as T[] or 数组<T> — both are equivalent. For example, 数字[] is an array of numbers and 字符串[] is an array of strings. You can nest them: 数字[][] is a 2D array (array of arrays of numbers). TypeScript also infers array element types from array literals, widening to the common type: [1, 2, 3] infers as 数字[], while [1, "two"] infers as (字符串 | 数字)[].

Tuple Types

A tuple is an array with a fixed number of elements, each with a specific type. You write it as [Type1, Type2, ...]. For example, [字符串, 数字] is a pair where position 0 is a string and position 1 is a number. Tuples are useful for returning multiple values, representing CSV rows, or modeling coordinate pairs. You can mark them readonly with readonly [字符串, 数字] to prevent mutation.

Readonly Arrays

The readonly modifier prevents array mutation: readonly 数字[] lets you read elements but not push, pop, or assign by index. This is useful for function parameters that should not be mutated. The ReadonlyArray<T> type is the equivalent named form. Readonly arrays enforce immutability at the type level, catching accidental mutations at compile time.

示例代码

              // Array types — two equivalent syntaxes.
let scores: number[] = [90, 85, 92];
let names: Array<string> = ["Alice", "Bob", "Carol"];

// 2D array — array of arrays.
let grid: number[][] = [[1, 2], [3, 4]];

// Tuple — fixed length, each position has a specific type.
let httpOk: [number, string] = [200, "OK"];
let point: [number, number] = [10, 20];

// Readonly tuple — cannot be mutated.
const fixed: readonly [string, number] = ["id", 42];
// fixed[0] = "name"; // ❌ Error: readonly

// Tuple with optional trailing element.
type Result = [number, string?];
const success: Result = [200, "done"];
const bare: Result = [404];

console.log(scores[0], httpOk[1], point, success, bare);
            

数组 use T[] or 数组<T>. Tuples fix 长度 and 每-位置类型. readonly prevents mutation. 可选 tuple 元素 use ? at 端.

动手试一试

常见错误

错误写法

Treating tuple 如 regular 数组 and pushing extra 元素

正确做法

Tuples 有 fixed 长度. Pushing 超出定义长度 violates 类型. 如果长度 varies, use regular 数组类型 T[] 相反.

错误写法

Forgetting 那个 tuple 元素顺序 matters

正确做法

[字符串, 数字] and [数字, 字符串] 是不同类型. 位置 0 必须 match 首先 declared 类型. 总是检查顺序当 assigning.

练习 数组 and Tuples in TypeScript

9 个练习

练习 数组 and Tuples in TypeScript

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误