外观
外观
怡然
1046字约3分钟
2024-10-29
ts数组有一个基本特征,所有成员的类型必须相同,但是数量是不确定的。 ts中数组的写法主要有以下两种:
// 第一种
let arr: number[] = [1, 2, 3];
let arr: (number | string)[];
// 第二种写法:ts内置的Array接口,这种写法本质上属于泛型
let arr: Array<number> = [1, 2, 3];
let arr: Array<number | string>;
TypeScript
允许使用方括号读取数组成员的类型。type Names = string[];
type Name = Names[0]; // string
// 类型Names是字符串数组,那么Names[0]返回的类型就是string。
type Name = Names[number]; // string
// Names[number]表示数组Names所有数值索引的成员类型,所以返回string。
any[]
。const arr = [];
arr; // 推断为 any[]
arr.push(123);
arr; // 推断类型为 number[]
arr.push("abc");
arr; // 推断类型为 (string|number)[]
const
断言readonly
关键字。const arr: readonly number[] = [0, 1];
arr[1] = 2; // 报错
arr.push(3); // 报错
delete arr[0]; // 报错
readonly
关键字不能与数组的泛型写法一起使用。TypeScript
提供了两个专门的泛型,用来生成只读数组的类型。const a1: ReadonlyArray<number> = [0, 1];
const a2: Readonly<number[]> = [0, 1];
const
断言。const arr = [0, 1] as const;
arr[0] = [2]; // 报错
TypeScript
使用T[][]
的形式,表示二维数组,T是最底层数组成员的类型。var multi: number[][] = [
[1, 2, 3],
[23, 24, 25],
];
元组(tuple)是
TypeScript
特有的数据类型,表示成员类型可以自由设置的数组。元组必须声明每个成员的类型。
const s: [string, string, boolean] = ["a", "b", true];
number[]
),元组的成员类型是写在方括号里面([number]
)。?
),表示该成员是可选的。let a: [number, number?] = [1];
...
),可以表示不限成员数量的元组。type NamedNums = [string, ...number[]];
const a: NamedNums = ["A", 1, 2];
const b: NamedNums = ["B", 1, 2, 3];
number
type Tuple = [string, number, Date];
type TupleEl = Tuple[number]; // string|number|Date 这个类型是三种值的联合类型。
// 写法一
type t = readonly [number, string];
// 写法二
type t = Readonly<[number, string]>;
type t1 = readonly [number, number];
type t2 = [number, number];
let x: t2 = [1, 2];
let y: t1 = x; // 正确
x = y; // 报错
TypeScript
会推断出元组的成员数量(即元组长度)。function f(point: [number, number]) {
if (point.length === 3) {
// 报错
// TypeScript 发现元组point的长度是2,不可能等于3,这个判断无意义
}
}
const arr = [1, 2];
function add(x: number, y: number) {
// ...
}
add(...arr); // 报错
const arr: [number, number] = [1, 2];
function add(x: number, y: number) {
// ...
}
add(...arr); // 正确