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"
}
};
편집: 문자열에 대한 테스트를 요청하도록 텍스트를 업데이트했습니다.[ 。이것은 이전의 코드 예시에만 기재되어 있었습니다.
테스트 할 수 없습니다.string[]
일반적인 경우이지만 테스트 할 수 있습니다.Array
JavaScript https://stackoverflow.com/a/767492/390330에서와 같은 기능을 쉽게 사용할 수 있습니다.Array.isArray(value)
).
특히 필요한 경우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[]!');
}
}
(기본형이 아닌) 클래스의 배열을 확인해야 하는 경우
if(items && (items.length > 0) && (items[0] instanceof MyClassName))
모든 항목이 동일한 유형인지 확실하지 않은 경우
items.every(it => it instanceof MyClassName)
다른 옵션은 Array.isArray()입니다.
if(! Array.isArray(classNames) ){
classNames = [classNames]
}
지금까지의 솔루션 중 가장 간결한 것은 다음과 같습니다.
function isArrayOfStrings(value: unknown): value is string[] {
return Array.isArray(value) && value.every(item => typeof item === "string");
}
는 반환되는 것에 주의해 주세요.true
빈 배열의 경우.되돌아가다false
빈 배열의 경우 condition 구에 추가합니다.
function isNonEmptyArrayOfStrings(value: unknown): value is string[] {
return Array.isArray(value) && value.length > 0 && value.every(item => typeof item === "string");
}
TypeScript에는 런타임 유형 정보가 없습니다(TypeScript Design Goals > Non goals, 5 참조).따라서 빈 어레이 요소의 "type"을 얻을 수 없습니다.비어 있지 않은 배열의 경우 항목 유형을 하나씩 확인하는 것밖에 할 수 없습니다.
형식 술어 value is string[]
유형을 좁히다value
로.string[]
해당하는 범위 내에서.이것은 TypeScript 기능으로 함수의 실제 반환 유형은 다음과 같습니다.boolean
.
답변이 끝난 것은 알고 있습니다만, 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) {
for (const item of 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[]
그래도 괜찮을 것 같아
이것을 시험해 보세요.
if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}
아래와 같이 간단하게 할 수 있습니다.
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ö의 코멘트 갱신
여기도 이용하실 수 있습니다.
const isStringArray = (test: any[]): boolean => {
return Array.isArray(test) && test.every((value) => typeof value === 'string')
}
여기에 약간의 문제가 있다 왜냐하면
if (typeof item !== 'string') {
return false
}
포어치를 멈추지 않습니다.따라서 배열에 문자열 값이 없는 경우에도 함수는 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;
}
안녕하세요, 한스
타입 가드(https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards),를 참조하면 ->와 같은 작업을 할 수 있습니다.
/**
* type-guard function to check at run-time if all the elements inside
* from the array are strings
* @param array
* @returns - boolean, true if the array is string array
*/
export function isStringArray(array: unknown[]): array is string[] {
return array.every((element) => typeof element === 'string')
}
언급URL : https://stackoverflow.com/questions/23130292/test-for-array-of-string-type-in-typescript
'programing' 카테고리의 다른 글
각도와 동일한 각도는 무엇입니까?JS $watch? (0) | 2023.02.25 |
---|---|
클래스 기반 컴포넌트에서 React.forwardRef를 사용하는 방법 (0) | 2023.02.25 |
'Access-Control-Allow-Origin' 헤더는 여러 값 '*, *'을 포함하지만 하나만 허용됩니다. (0) | 2023.02.25 |
MongoDB: '_id'가 아닌 'id' 출력 (0) | 2023.02.25 |
Angular 배열에서 항목을 제거하는 방법JS 스코프? (0) | 2023.02.25 |