TypeScript 中声明只接受特定值的数组
使用联合类型来声明一个只接受特定值的数组,例如 const arr2: ('a' | 'b' | 'c')[] = []
。 联合类型由两个或多个其他类型或文字组成。 示例中的数组只能包含字符串 a、b 和 c。
type NumbersLessThan5 = 1 | 2 | 3 | 4;
const arr: NumbersLessThan5[] = [];
arr.push(1);
arr.push(2);
arr.push(3);
arr.push(4);
我们使用联合类型来创建一个只接受特定值的数组。
示例中的数组只能包含数字 1-4。 如果我们尝试将一个不包含在联合类型中的数字添加到数组中,我们会得到一个错误。
type NumbersLessThan5 = 1 | 2 | 3 | 4;
const arr: NumbersLessThan5[] = [];
// ⛔️ Error: Argument of type '5' is not
// assignable to parameter of type 'NumbersLessThan5'.ts(2345)
arr.push(5);
这在使用字符串文字时以相同的方式工作。
type FirstThreeLetters = 'a' | 'b' | 'c';
const arr2: FirstThreeLetters[] = [];
arr2.push('a');
arr2.push('b');
arr2.push('c');
// ⛔️ Error: Argument of type '"d"' is not
// assignable to parameter of type 'FirstThreeLetters'.ts(2345)
arr2.push('d');
这些值不必是同一类型。 在不太可能出现的混合数组情况下,我们可以使用相同的方法。
type Mixed = 'a' | 'b' | 1;
const arr2: Mixed[] = [];
arr2.push('a');
arr2.push('b');
arr2.push(1);
联合类型在 TypeScript 中非常有用,实际上布尔类型只是联合 true | false
的别名。
相关文章
将 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 数组。