在 TypeScript 中声明一个具有最小长度的数组
使用元组声明具有最小长度的数组,例如 let arrMinLength2: [string, string, ...string[]] = ['a', 'b']
。 元组类型允许我们表达一个包含固定数量元素的数组,这些元素的类型是已知的,但可以不同。
// ✅ First approach
let arrMinLength2: [string, string, ...string[]] = ['a', 'b'];
arrMinLength2 = ['a', 'b', 'c']; // ✅ OK
// ⛔️ Error: Source has 1 element(s) but target requires 2.
arrMinLength2 = ['a'];
// ✅ Second approach
type Tuple3<T> = [T, T, T];
type Tuple6<T> = [...Tuple3<T>, ...Tuple3<T>];
// ⛔️ Source has 2 element(s) but target requires 3.
const arrMinLength3: Tuple3<string> = ['a', 'b'];
在第一个示例中,我们声明了一个最小长度为 2 个字符串类型元素的元组。
...string[]
语法在元组类型中称为 Rest 元素,表示该元组是开放式的,可以具有零个或多个指定类型的附加元素。
例如,[string, ...boolean[]]
表示一个元组,其第一个元素为字符串,后跟任意数量的布尔元素。
元组可以包含 2 个以上的元素,但如果我们尝试用少于 2 个元素重新声明它,则会出现错误。
let arrMinLength2: [string, string, ...string[]] = ['a', 'b'];
arrMinLength2 = ['a', 'b', 'c']; // ✅ OK
// ⛔️ Error: Source has 1 element(s) but target requires 2.
arrMinLength2 = ['a'];
如果我们向数组中添加了正确数量的元素,但混淆了类型,也会出现错误。
let arrMinLength2: [string, string, ...string[]] = ['a', 'b'];
// ⛔️ Error: Type 'number' is not
// assignable to type 'string'.ts(2322)
arrMinLength2 = ['a', 4]; // ✅ OK
元组类型用于表示具有固定数量元素的数组,这些元素的类型是已知的,但可以不同。
话虽如此,元组由数组表示,我们仍然可以调用 pop()
方法从元组中删除元素。
const arrMinLength2: [string, string, ...string[]] = ['a', 'b'];
arrMinLength2.pop();
arrMinLength2.pop();
console.log(arrMinLength2); // 👉️ []
如果要防止这种情况发生,可以将元组声明为readonly
。
const arrMinLength2: readonly [string, string, ...string[]] = ['a', 'b'];
// ⛔️ Error: Property 'pop' does not exist
// on type 'readonly [string, string, ...string[]]'.ts(2339)
arrMinLength2.pop();
但这也意味着我们无法更改元组元素的值或添加更多元素。
或者,我们可以使用以下方法声明一个最小长度为 N 的数组。
type Tuple3<T> = [T, T, T];
type Tuple6<T> = [...Tuple3<T>, ...Tuple3<T>];
// ⛔️ Source has 2 element(s) but target requires 3.
const arrMinLength3: Tuple3<string> = ['a', 'b'];
当我们使用较长的数组时,这很有用,因为我们可以声明一个包含 N 个元素的元组,并使用扩展语法
...
根据需要多次将该元组解压缩为一个新元组。
如果我们需要声明一个最大长度为 N 的数组,请使用具有可选值的元组。
// ✅ Array of Max length
let arrOfMaxLength3: [string?, string?, string?] = [];
arrOfMaxLength3 = ['a', 'b', 'c']; // ✅ OK
arrOfMaxLength3 = ['a', 'b']; // ✅ OK
arrOfMaxLength3 = ['a']; // ✅ OK
// ⛔️ Error: Source has 4 element(s) but target allows only 3.
arrOfMaxLength3 = ['a', 'b', 'c', 'd'];
问号用于将元组中的值标记为可选。 示例中的元组最多可以有 3 个元素(除非你使用数组方法添加更多)。
相关文章
将 NumPy 数组转换为 Pandas DataFrame
发布时间:2024/04/21 浏览次数:111 分类:Python
-
本教程介绍了如何使用 pandas.DataFrame()方法从 NumPy 数组生成 Pandas DataFrame。
如何将 Pandas Dataframe 转换为 NumPy 数组
发布时间:2024/04/20 浏览次数:176 分类:Python
-
本教程介绍如何将 Pandas Dataframe 转换为 NumPy 数组的方法,例如 to_numpy,value 和 to_records
在 Python 中将 Tensor 转换为 NumPy 数组
发布时间:2024/03/12 浏览次数:131 分类:Python
-
在 Python 中,可以使用 3 种主要方法将 Tensor 转换为 NumPy 数组:Tensor.numpy()函数,Tensor.eval()函数和 TensorFlow.Session()函数。
在 Python 中将 CSV 读取为 NumPy 数组
发布时间:2024/03/12 浏览次数:133 分类:Python
-
本教程演示如何在 Python 中将 CSV 读取为 NumPy 数组。