检查 Value 是否是 TypeScript 中的(类型)数组

检查 Value 是否为 TypeScript 中的数组(类型)

Check if a Value is an Array (of type) in TypeScript

要检查一个值是否是 TypeScript 中特定类型的数组:

  1. 使用Array.isArray()方法检查值是否为数组。
  2. 遍历数组并检查每个值是否属于特定类型。
索引.ts
const arr: string[] = ['bobby', 'hadz', 'com']; const isArray = Array.isArray(arr); // 👉️ true if (Array.isArray(arr)) { const isStringArray = arr.length > 0 && arr.every((value) => { return typeof value === 'string'; }); console.log(isStringArray); // 👉️ true }

您可以使用
Array.isArray
方法检查值是否为 TypeScript 中的数组。

索引.ts
console.log(Array.isArray([])); // 👉️ true console.log(Array.isArray({})); // 👉️ false console.log(Array.isArray('bobbyhadz.com')); // 👉️ false const arr = ['bobby', 'hadz', 'com']; if (Array.isArray(arr)) { // 👇️ this runs console.log('The value is an array'); } else { console.log('The value is not an array'); }

如果提供的值是数组,则Array.isArray()方法返回,否则返回。truefalse

我还写了一篇关于
如何从数组类型中获取数组元素类型的文章。

检查一个值是否是 TypeScript 中特定类型的数组

如果需要检查值是否为特定类型的数组,则必须遍历数组的元素并检查每个元素是否为特定类型。

索引.ts
const arr: string[] = ['bobby', 'hadz', 'com']; if (Array.isArray(arr)) { const isStringArray = arr.length > 0 && arr.every((value) => { return typeof value === 'string'; }); console.log(isStringArray); // 👉️ true }

Array.every
方法检查数组中的所有元素是否都
通过
回调函数实现的测试。

true如果所有元素都通过测试,则该方法返回,false否则返回。

如果该函数返回一个假值,该every()方法将短路并返回false

如果所有数组元素都满足条件,则该every方法返回
true

请注意,我们做的第一件事是检查数组是否不为空。

索引.ts
const arr: string[] = ['bobby', 'hadz', 'com']; if (Array.isArray(arr)) { const isStringArray = arr.length > 0 && arr.every((value) => { return typeof value === 'string'; }); console.log(isStringArray); // 👉️ true }
Calling the every() method on an empty array will always return true regardless of the implemented condition.

This is why we check if the array has more than 0 elements – to avoid any
false positives.

If the callback function we passed to the every() method returns true on all
iterations, the every() method will also return true.

This is the only way to check if all of the elements in the array are of a
specific type.

If you aren’t fetching the array from a remote source, e.g. an API, and you’re
using TypeScript, you can pretty much assume that the array contains elements of
the expected type unless you used any or
type assertions
when working with the array.

如果您需要
检查 TS 中变量的类型,请单击链接并按照说明进行操作。

我还写了一篇关于
如何检查数组是否包含 TS 中的值的文章。