[typescript] TypeScript에서 문자열 유형의 배열 테스트

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

편집 : 문자열 []에 대한 테스트를 요청하기 위해 텍스트를 업데이트했습니다. 이것은 이전의 코드 예제에만있었습니다.



답변

당신은 테스트 할 수없는 string[]일반적인 경우에 그러나 당신은 테스트 할 수 있습니다 Array자바 스크립트로 아주 쉽게 같은 https://stackoverflow.com/a/767492/390330

특별히 string배열을 원한다면 다음과 같이 할 수 있습니다.

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[]!');
   }
}


답변

또 다른 옵션은 Array.isArray ()입니다.

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


답변

지금까지 가장 간결한 솔루션은 다음과 같습니다.

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

참고 value.every반환 true빈 배열. false빈 배열 을 반환해야하는 경우 value.length조건 절에 추가해야합니다 .

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

TypeScript에는 런타임 유형 정보가 없으므로 (없을 것입니다. TypeScript Design Goals> Non goals , 5 참조), 빈 배열의 유형을 가져올 방법이 없습니다. 비어 있지 않은 배열의 경우 항목 유형을 하나씩 확인하는 것뿐입니다.


답변

나는 이것에 대한 답을 알고 있지만 TypeScript는 유형 가드를 도입했습니다 : https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards

다음 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
  }
}

빈 배열이으로 입력되는 문제 string[]가 있지만 괜찮을 수 있습니다.


답변

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

나는이 접근법이 다른 것보다 낫다고 믿습니다. 이것이 제가이 답변을 게시하는 이유입니다.

Sebastian Vittersø의 의견에 대한 업데이트

여기 Array.prototype.every()에서도 사용할 수 있습니다 .

const isStringArray = (test: any[]): boolean => {
 return Array.isArray(test) && test.every((value) => typeof value === 'string')
}


답변

이 시도:

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


답변

여기에 약간의 문제가 있습니다.

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

foreach를 멈추지 않을 것입니다. 따라서 배열에 문자열 값이없는 경우에도 함수는 true를 반환합니다.

이것은 나를 위해 일한 것 같습니다.

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;
}

인사, 한스