在 TypeScript 中定义一个字符串数组
要定义字符串数组,请将数组的类型设置为 string[]
,例如 const arr: string[] = []
。 如果我们尝试将任何其他类型的值添加到数组中,类型检查器将显示错误。
// ✅ 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 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[]
。
// ?️ const arr2: any[]
const arr2 = [];
TypeScript 不知道我们将向数组添加什么类型的值,因此它使用非常广泛的 any
类型。
这意味着我们可以将任何类型的值添加到数组中,但我们不会从类型检查器中获得任何帮助。
我们应该始终明确设置空数组的类型。
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 推断它的类型。
// ?️ const arr: string[]
const arr = ['a', 'b', 'c'];
我们还可以使用类型来定义字符串数组。
type Colors = string[];
const arr3: Colors = ['red', 'blue', 'green'];
如果有一个具有字符串数组属性的对象,我们也可以使用接口。
interface Colorful {
colors: string[];
}
const arr3: Colorful = {
colors: ['red', 'blue', 'green'],
};
在某些情况下,我们可能知道数组将只有 N 个特定类型的元素。 在这种情况下,我么可以使用元组。
// ?️ const arr: [string, string]
const arr: [string, string] = ['hello', 'world'];
我们在上面声明的 arr 变量是一个包含 2 个字符串的元组。
如果我们需要声明一个只读字符串数组,请使用 Readonly
实用程序类型。
const arr: Readonly<string[]> = ['hello', 'world'];
// ⛔️ Property 'push' does not exist
// on type 'readonly string[]'.ts(2339)
arr.push('test');
我们将 string[]
类型传递给 Readonly
实用程序类型,因此该数组只能读取,但不能更改。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。