Array and tuple types
TypeScript provides multiple ways to describe structured data, with arrays and tuples being the two most fundamental composite types. Both can store ordered collections of elements, but they differ significantly in usage scenarios and type constraints.
Array Type Basics
Array types represent variable-length sequences of elements of the same type. TypeScript offers two equivalent syntaxes for declaring array types:
// Element type followed by square brackets
let numbers: number[] = [1, 2, 3];
// Using the generic array type
let strings: Array<string> = ["a", "b"];
Array types enforce that all elements must be of the same type. When attempting to mix types, TypeScript throws an error:
// Type error: Cannot assign a string to a number array
numbers.push("4"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'
Array Type Inference
TypeScript can automatically infer array types based on initialization values. Empty arrays require explicit annotation; otherwise, they are inferred as any[]
:
let inferredArray = [1, 2, 3]; // Automatically inferred as number[]
let emptyArray = []; // Type is any[]
let typedEmptyArray: string[] = []; // Explicit annotation
Readonly Arrays
Use ReadonlyArray
or the readonly
modifier to create immutable arrays:
const roArray: ReadonlyArray<number> = [1, 2, 3];
roArray.push(4); // Error: Property 'push' does not exist on type 'ReadonlyArray<number>'
// Using a more concise syntax
const roNumbers: readonly number[] = [1, 2, 3];
Tuple Type Basics
Tuple types allow representing arrays with a known number of elements, where each element can have a different type:
let person: [string, number] = ["Alice", 30];
Tuples strictly validate element positions and types:
person = [30, "Alice"]; // Error: Type 'number' is not assignable to type 'string'
person[2] = true; // Error: Tuple type '[string, number]' of length '2' has no element at index '2'
Optional Tuple Elements
Tuples can mark optional elements with a question mark:
type OptionalTuple = [string, number?];
const a: OptionalTuple = ["hello"]; // Valid
const b: OptionalTuple = ["world", 42]; // Valid
Rest Elements and Open-Ended Tuples
Tuples can use rest syntax to represent variable-length sections:
type StringNumberBooleans = [string, number, ...boolean[]];
const snb: StringNumberBooleans = ["hello", 1, true, false, true];
Differences Between Tuples and Arrays
- Length Handling:
// Array length is mutable
const arr: number[] = [1];
arr.push(2); // Valid
// Tuple length is fixed
const tuple: [number] = [1];
tuple.push(2); // Type check passes but violates tuple design intent
- Destructuring Behavior:
const rgb: [number, number, number] = [255, 0, 128];
const [red, green, blue] = rgb; // Precise destructuring
const color = [255, 0, 128]; // number[] type
const [r, g, b] = color; // Destructured types are all number
Practical Use Cases
Typical Array Use Cases:
// Handling homogeneous data collections
function sum(values: number[]): number {
return values.reduce((a, b) => a + b, 0);
}
Typical Tuple Use Cases:
// React useState return type
type StateHook<T> = [T, (newValue: T) => void];
function useState<T>(initial: T): StateHook<T> {
// Implementation omitted
}
// CSV line processing
function parseCSVLine(line: string): [string, number, Date] {
// Parsing logic
return ["Alice", 30, new Date()];
}
Type Operations and Advanced Features
Union Type Arrays:
let mixedArray: (string | number)[] = ["text", 42];
Const Assertions:
const point = [10, 20] as const; // Type is readonly [10, 20]
Mapped Type Transformations:
type TupleToObject<T extends readonly any[]> = {
[K in keyof T]: { value: T[K] }
};
type ObjTuple = TupleToObject<[string, number]>;
// Result is [{ value: string }, { value: number }]
Common Issues and Solutions
Tuple Length Overflow:
function processTuple(t: [string, number]) {
// ...
}
const input = ["test", 1, "extra"] as const;
processTuple(input); // Error: Source has 3 elements but target allows only 2
// Solution 1: Type assertion
processTuple(input as [string, number]);
// Solution 2: Precise type definition
function processDynamicTuple(t: readonly [string, number, ...unknown[]]) {
const [first, second] = t;
// ...
}
Mutating Tuple Members:
const tuple: [string, number] = ["a", 1];
tuple[0] = "b"; // Valid but may not align with design intent
// Defensive approach
type ImmutableTuple = readonly [string, number];
const immutable: ImmutableTuple = ["a", 1];
immutable[0] = "b"; // Error: Cannot assign to '0' because it is a read-only property
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:原始类型与字面量类型
下一篇:对象类型与接口