TypeScrip中字符串类型数组的测试

2024-09-27 19:30:35 发布

您现在位置:Python中文网/ 问答频道 /正文

如何测试变量是否是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此处:http://typescript.io/k0ZiJzso0Qg/2

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


Tags: no字符串iostringreturnifvaras
3条回答

以下是迄今为止最简明的解决方案:

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

注意,^{}将返回空数组的true。如果需要返回空数组的false,则应将^{}添加到condition子句中:

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

TypeScript中没有任何运行时类型信息(也不会有,请参见TypeScript Design Goals > Non goals,5),因此无法获取空数组的类型。对于非空数组,您只能逐个检查其项的类型。

另一个选项是Array.isArray()

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

在一般情况下,您不能测试string[],但是可以很容易地测试Array,就像在JavaScript中一样https://stackoverflow.com/a/767492/390330

如果您特别需要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[]!');
   }
}

相关问题 更多 >

    热门问题