在 TypeScript 中定义一个字符串数组

在 TypeScript 中定义一个字符串数组

Define an Array of Strings in TypeScript

要定义字符串数组,请将数组的类型设置为string[],例如
const arr: string[] = []如果您尝试向数组添加任何其他类型的值,类型检查器将显示错误。

索引.ts
// ✅ Array of strings with inline declaration const arr: string[] = ['red', 'blue', 'green']; // ✅ Empty array of strings const arr2: string[] = []; // ✅ Using a type type Colors = string[]; const arr3: Colors = ['red', 'blue', 'green'];

第一个示例展示了如何定义具有内联类型的字符串数组。

如果您尝试将任何其他类型的值添加到数组中,则会出现错误。

索引.ts
const arr: string[] = ['red', 'blue', 'green']; // ⛔️ Error: Argument of type 'number' is // not assignable to parameter of type 'string'.ts(2345) arr.push(100);

当您必须将数组初始化为空时,这种方法非常有用。如果您没有显式键入空数组,TypeScript 会假定其类型为
any[].

索引.ts
// 👇️ const arr2: any[] const arr2 = [];

TypeScript 不知道我们将向数组添加什么类型的值,因此它使用非常广泛的any类型。

这意味着我们可以将anytype 的值添加到数组中,但我们不会从类型检查器那里得到任何帮助。

您应该始终显式设置空数组的类型。

索引.ts
const arr: string[] = ['red', 'blue', 'green']; const arr2: string[] = []; // ✅ Works arr2.push('hello'); // ⛔️ Error: Argument of type 'number' is not // assignable to parameter of type 'string'.ts(2345) arr2.push(100);

另一方面,如果你用值初始化数组,你可以让 TypeScript 推断它的类型。

索引.ts
// 👇️ const arr: string[] const arr = ['a', 'b', 'c'];

您还可以使用类型来定义字符串数组。

索引.ts
type Colors = string[]; const arr3: Colors = ['red', 'blue', 'green'];

如果您的对象的属性是字符串数组,您也可以使用接口。

索引.ts
interface Colorful { colors: string[]; } const arr3: Colorful = { colors: ['red', 'blue', 'green'], };

在某些情况下,您可能知道数组将只有 N 个特定类型的元素。您可以在这种情况下使用元组。

索引.ts
// 👇️ const arr: [string, string] const arr: [string, string] = ['hello', 'world'];

我们上面声明的arr变量是一个包含2字符串的元组。

如果您需要声明一个readonly字符串数组,请使用
Readonly
实用程序类型。

索引.ts
const arr: Readonly<string[]> = ['hello', 'world']; // ⛔️ Property 'push' does not exist // on type 'readonly string[]'.ts(2339) arr.push('test');

我们将string[]类型传递给Readonly实用程序类型,因此数组只能读取,不能更改。

发表评论