Test for array of string type in TypeScript

后端 未结 7 2034
礼貌的吻别
礼貌的吻别 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:52

    I know this has been answered, but TypeScript introduced type guards: 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:

    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(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

提交回复
热议问题