TypeScript 中定义具有多种类型的数组

使用联合类型在 TypeScript 中定义具有多种类型的数组,例如 const arr: (string | number)[] = [‘a’, 1]。 联合类型由两个或多个其他类型组成。 示例中的数组只能包含字符串和数字类型的值。

const arr1: (string | number)[] = ['a', 'b', 1, 2];

我们使用联合类型来创建具有多种类型的数组。

联合类型可以根据需要由任意多的类型构成。

const arr1: (string | number | boolean)[] = ['a', 1, true];

如果我们尝试将一个元素添加到与联合不兼容的类型的数组中,则会出现错误。

const arr1: (string | number)[] = ['a', 1];

// ⛔️ Error: Argument of type '{ hello: string; }' is
// not assignable to parameter of type 'string | number'.
arr1.push({ hello: 'world' });

我们还可以使用这种方法来定义一个包含多种类型对象的数组。

type Bird = {
  canFly: boolean;
};

type Dog = {
  canSwim: boolean;
};

const bird: Bird = {
  canFly: true,
};

const dog: Dog = {
  canSwim: false,
};

const arr1: (Bird | Dog)[] = [bird, dog];

if ('canFly' in arr1[0]) {
  console.log(arr1[0].canFly); // ?️ true
} else {
  console.log(arr1[0].canSwim);
}

我们有 Bird 和 Dog 类型的对象,它们具有不同的属性和类型。 该数组可以包含两种类型的元素。

请注意 ,我们必须使用类型保护才能访问数组中对象的属性。

canFly 属性只包含在 Bird 类型中,因此在我们能够访问该属性之前,我们必须确保数组中的元素是 Bird 类型。

如果我们有一个包含多种类型并具有预定义长度和顺序的数组,则可以使用元组。

const arr: [string, number] = ['x', 100];

我们指定上面数组中的第一个元素是字符串类型,第二个元素是数字类型。

元组类型允许我们用固定数量的元素来表达一个数组,这些元素的类型是已知的,但可以不同。

这很有用,因为如果你不正确地初始化数组,你会得到一个错误。

// ⛔️ Error: Type 'number' is not
// assignable to type 'string'.ts(2322)
const arr: [string, number] = [100, 'x'];

当访问现有索引处的元素时,TypeScript 知道值的类型。

const arr: [string, number] = ['x', 100];

// ✅ TypeScript knows first element is string
console.log(arr[0].toUpperCase()); // ?️ "X"

// ✅ TypeScript knows second element is number
console.log(arr[1].toFixed(2)); // ?️ 100.00

如果我们尝试访问索引不存在的元组元素,类型检查器会抛出错误。

const arr: [string, number] = ['x', 100];

// ⛔️ Error: Tuple type '[string, number]' of length '2'
// has no element at index '2'.ts(2493)
console.log(arr[2]);

如果使用 const 关键字来声明元组,则必须使用已为其指定类型的所有值来初始化数组。

// ⛔️ Error: Type '[string]' is not assignable
// to type '[string, number]'.
// Source has 1 element(s) but target requires 2.ts(2322)
const arr: [string, number] = ['x'];

如果在初始化数组时没有所有必要的值,请使用 let 关键字来声明元组。