Test for array of string type in TypeScript

后端 未结 7 2006
礼貌的吻别
礼貌的吻别 2020-12-03 02:32

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

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

         


        
7条回答
  •  死守一世寂寞
    2020-12-03 02:49

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

    If you specifically want for string array you can do something like:

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

提交回复
热议问题