在 TypeScript 中测试字符串类型的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23130292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:13:50  来源:igfitidea点击:

Test for array of string type in TypeScript

typescript

提问by Sean Kearon

How can I test if a variable is an array of string in TypeScript? Something like this:

如何测试变量是否是 TypeScript 中的字符串数组?像这样的东西:

function f(): string {
    var a: string[] = ["A", "B", "C"];

    if (typeof a === "string[]")    {
        return "Yes"
    }
    else {
        // returns no as it's 'object'
        return "No"
    }
};

TypeScript.io here: http://typescript.io/k0ZiJzso0Qg/2

TypeScript.io 在这里:http: //typescript.io/k0ZiJzso0Qg/2

Edit: I've updated the text to ask for a test for string[]. This was only in the code example previously.

编辑:我已更新文本以要求对字符串 [] 进行测试。这仅在之前的代码示例中。

回答by basarat

You cannot test for string[]in the general case but you can test for Arrayquite easily the same as in JavaScript https://stackoverflow.com/a/767492/390330

您无法string[]在一般情况下进行测试,但您可以Array像在 JavaScript 中一样轻松地进行测试https://stackoverflow.com/a/767492/390330

If you specifically want for stringarray you can do something like:

如果您特别想要string数组,您可以执行以下操作:

if (value instanceof Array) {
   var somethingIsNotString = false;
   value.forEach(function(item){
      if(typeof item !== 'string'){
         somethingIsNotString = true;
      }
   })
   if(!somethingIsNotString && value.length > 0){
      console.log('string[]!');
   }
}

回答by grigson

Another option is Array.isArray()

另一种选择是Array.isArray()

if(! Array.isArray(classNames) ){
    classNames = [classNames]
}

回答by axmrnv

Here is the most concise solution so far:

这是迄今为止最简洁的解决方案:

function isArrayOfStrings(value: any): boolean {
   return Array.isArray(value) && value.every(item => typeof item === "string");
}

Note that value.everywill return truefor an empty array. If you need to return falsefor an empty array, you should add value.lengthto the condition clause:

请注意,这value.every将返回true一个空数组。如果你需要返回false一个空数组,你应该添加value.length到条件子句中:

function isNonEmptyArrayOfStrings(value: any): boolean {
    return Array.isArray(value) && value.length && value.every(item => typeof item === "string");
}

There is no any run-time type information in TypeScript (and there won't be, see TypeScript Design Goals > Non goals, 5), so there is no way to get the type of an empty array. For a non-empty array all you can do is to check the type of its items, one by one.

TypeScript 中没有任何运行时类型信息(并且不会有,请参阅TypeScript 设计目标 > 非目标,5),因此无法获取空数组的类型。对于非空数组,您所能做的就是一一检查其项目的类型。

回答by Nicholas Boll

I know this has been answered, but TypeScript introduced type guards: https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards

我知道这已经得到回答,但 TypeScript 引入了类型保护:https: //www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards

If you have a type like: Object[] | string[]and what to do something conditionally based on what type it is - you can use this type guarding:

如果你有这样的类型:Object[] | string[]以及根据它是什么类型有条件地做某事 - 你可以使用这种类型保护:

function isStringArray(value: any): value is string[] {
  if (value instanceof Array) {
    value.forEach(function(item) { // maybe only check first value?
      if (typeof item !== 'string') {
        return false
      }
    })
    return true
  }
  return false
}

function join<T>(value: string[] | T[]) {
  if (isStringArray(value)) {
    return value.join(',') // value is string[] here
  } else {
    return value.map((x) => x.toString()).join(',') // value is T[] here
  }
}

There is an issue with an empty array being typed as string[], but that might be okay

将空数组输入为 存在问题string[],但这可能没问题

回答by Sudarshana Dayananda

You can have do it easily using Array.prototype.some()as below.

您可以使用Array.prototype.some()以下方法轻松完成。

const isStringArray = (test: any[]): boolean => {
 return Array.isArray(test) && !test.some((value) => typeof value !== 'string')
}
const myArray = ["A", "B", "C"]
console.log(isStringArray(myArray)) // will be log true if string array

I believe this approach is better that others. That is why I am posting this answer.

我相信这种方法比其他方法更好。这就是我发布这个答案的原因。

回答by Tcanarchy

Try this:

尝试这个:

if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}

回答by hans

there is a little problem here because the

这里有一个小问题,因为

if (typeof item !== 'string') {
    return false
}

will not stop the foreach. So the function will return true even if the array does contain none string values.

不会停止 foreach。因此,即使数组不包含任何字符串值,该函数也将返回 true。

This seems to wok for me:

这似乎对我有用:

function isStringArray(value: any): value is number[] {
  if (Object.prototype.toString.call(value) === '[object Array]') {
     if (value.length < 1) {
       return false;
     } else {
       return value.every((d: any) => typeof d === 'string');
     }
  }
  return false;
}

Greetings, Hans

问候,汉斯