如何检查数组中值的类型

huangapple go评论114阅读模式
英文:

How to check the type of values in an array

问题

以下是翻译好的内容:

我有一个类型为 string[] | object[] 的值,根据数组中值的类型,我想执行不同的操作。是否有一种方法可以检查数组中值的类型?

我尝试过检查数组中的第一个项目的类型,但 TypeScript 不识别它,因此仍然认为它可以是 string[] | object[]
我还尝试使用 every 并检查每个值的类型,但 TypeScript 不允许在 string[] | object[] 上使用 everyfilter

英文:

I have a value that has the type string[] | object[] and depending of the type of the values in the array I want to do different things with it. Is there a way to check the types of the values in the array?

I have tried checking the type of the first item in the array, but TypeScript doesn't recognise that, so it still thinks it can be a string[] | object[].
I also tried using every and check the type of every value but TypeScript doesn't allow the use of every or filter on string[] | object[]

答案1

得分: 1

由于您的数组被定义为 string[] | object[],因此编写类型断言来确定其最终类型是有意义的。这是如何使用它的示例:

function isStringArr(a_arr: string[] | object[]): a_arr is string[] {
    return !a_arr.some(a_item => typeof a_item !== 'string');
}

if(isStringArr(arr)){
    console.log(arr); // string[]
}
英文:

Since your array is defined as string[] | object[], then it makes sense to write a type predicate to find out what type it ends up being:

function isStringArr(a_arr: string[] | object[]): a_arr is string[] {
    return !a_arr.some(a_item => typeof a_item !== 'string');
}

This is how you would use it:

if(isStringArr(arr)){
    console.log(arr); // string[]
}

Checking the type in a for or forEach loop on every element is also possible, but since your array is either string[] OR object[] this doesn't make a whole lot of sense to do.

Playground with a few examples

答案2

得分: 0

const arr: string[] = ['a', 'b', 'c'];
// 检查变量的类型
const isArray = Array.isArray(arr); // 🔍 true
console.log(isArray);
// 检查数组中值的类型
if (Array.isArray(arr)) {
const isStringArray =
arr.length > 0 &&
arr.every((value) => {
return typeof value === 'string';
});

console.log(isStringArray); // 🔍 true
}

英文:
const arr: string[] = ['a', 'b', 'c'];
//check the type of variable
const isArray = Array.isArray(arr); // 👉️ true
console.log(isArray)
//check the type of values in array
if (Array.isArray(arr)) {
const isStringArray =
 arr.length > 0 &&
 arr.every((value) => {
 return typeof value === 'string';
});

  console.log(isStringArray); // 👉️ true
}

huangapple
  • 本文由 发表于 2023年4月19日 16:22:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052240.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定