배열에서 Null을 필터링하여 제외합니다.
TypeScript,--strictNullChecks
한 문자열 합니다.(string | null)[]
. 결과가 type을 가지도록 모든 null을 삭제하는 단일 표현 방법은 무엇입니까?string[]
const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = ???;
Array.filter는 여기서 작동하지 않습니다.
// Type '(string | null)[]' is not assignable to type 'string[]'
array.filter(x => x != null);
어레이 압축은 동작할 수 있지만 TypeScript에서는 지원되지 않습니다.
실제로 이 질문은 유니언에서 특정 유형의 엔트리를 삭제함으로써 임의의 유니언 유형의 배열을 필터링하는 문제로 일반화할 수 있습니다.그러나 이러한 조합이 가장 일반적인 사용 사례이기 때문에 무효 또는 정의되지 않은 조합에 초점을 맞추도록 하겠습니다.
타입 술어 함수는,.filter
엄격한 유형 검사에서 제외되지 않도록 하려면:
function notEmpty<TValue>(value: TValue | null | undefined): value is TValue {
return value !== null && value !== undefined;
}
const array: (string | null)[] = ['foo', 'bar', null, 'zoo', null];
const filteredArray: string[] = array.filter(notEmpty);
에 '하다'를 사용할 수도 .array.reduce<string[]>(...)
.
2021 업데이트: 보다 엄격한 술어
이 솔루션은 대부분의 시나리오에서 작동하지만 술어에서 더 엄격한 유형 검사를 받을 수 있습니다.바와 같이 과 같습니다.notEmpty
이 '비밀번호'인지 은 아닙니다.null
★★★★★★★★★★★★★★★★★」undefined
반환문을 반환하다로 줄여보세요.return value !== null;
반환되는 경우에도 true
undefined
.
이를 완화하기 위한 한 가지 방법은 먼저 제어 흐름 블록을 사용하여 유형을 제한한 다음 더미 변수를 사용하여 컴파일러에 확인할 무언가를 제공하는 것입니다.는 '보다 낫다'는 것을 할 수 .value
는 a로 지정할 수 .null
★★★★★★★★★★★★★★★★★」undefined
, 을 삭제하면|| value === undefined
에러가 되며 위의알수 있습니다.
function notEmpty<TValue>(value: TValue | null | undefined): value is TValue {
if (value === null || value === undefined) return false;
const testDummy: TValue = value;
return true;
}
주의: 이 방법으로도 실패할 수 있는 상황이 있습니다.위반과 관련된 문제에 유의하십시오.
@@bijou-trouvailu, @bijou-trouvailu를 .<arg> is <Type>
필터 기능의 출력으로 사용합니다.
array.filter((x): x is MyType => x !== null);
에 한 가지 더 이 있다.flatMap
명령어는 ""를 처리할 수 .filter
★★★★★★★★★★★★★★★★★」map
)string[]
// (string | null)[]
const arr = ["a", null, "b", "c"];
// string[]
const stringsOnly = arr.flatMap(f => f ? [f] : []);
라이너 1개:
const filteredArray: string[] = array.filter((s): s is string => Boolean(s));
이 방법은 형식 술어를 전달하는 것입니다.:s is string
구문)을 참조해 주세요.
이 답변은 을 나타내고 있다.Array.filter
에서는 사용자가 유형 술어를 제공해야 합니다.
됩니다.filter
결과를 원하는 유형으로 만듭니다.
const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray = array.filter(x => x != null) as string[];
이 방법은 다음과 같은 일반적인 사용 사례에 적용됩니다.
const array2: (string | number)[] = ["str1", 1, "str2", 2];
const onlyStrings = array2.filter(x => typeof x === "string") as string[];
const onlyNumbers = array2.filter(x => typeof x === "number") as number[];
(운동장 코드)
이렇게 할 수 있다는 것을 방금 깨달았습니다.
const nonNull = array.filter((e): e is Exclude<typeof e, null> => e !== null)
그럼으로써, 다음과 같은 것이 가능하게 됩니다.
- 추가 기능을 사용하지 않고 원라이너만 사용 가능
- 배열 요소의 유형을 알 필요가 없으므로 어디에나 복사할 수 있습니다.
의 가드 도우미 해서 쓸 저는 '가드 '라는 .isPresent
,isDefined
★★★★★★★★★★★★★★★★★」isFilled
https://www.npmjs.com/package/ts-is-present 에 접속합니다.
유형 정의는 현재 다음과 같습니다.
export declare function isPresent<T>(t: T | undefined | null): t is T;
export declare function isDefined<T>(t: T | undefined): t is T;
export declare function isFilled<T>(t: T | null): t is T;
다음과 같이 사용할 수 있습니다.
import { isDefined } from 'ts-is-present';
type TestData = {
data: string;
};
const results: Array<TestData | undefined> = [
{ data: 'hello' },
undefined,
{ data: 'world' }
];
const definedResults: Array<TestData> = results.filter(isDefined);
console.log(definedResults);
Typescript에서 이 기능을 번들하면 패키지를 제거합니다.하지만 지금은 즐기세요.
있다, 하다, 하다, 하다를 .NonNullable
@bijou-trouvailu가 더
function notEmpty<TValue>(value: TValue): value is NonNullable<TValue> {
return value !== null && value !== undefined;
}
const array: (string | null | undefined)[] = ['foo', 'bar', null, 'zoo', undefined];
const filteredArray: string[] = array.filter(notEmpty);
console.log(filteredArray)
[LOG]: ["foo", "bar", "zoo"]
Lodash를 하고 있는 는, 「Lodash」를 사용할 수 .compact
람다를에도 '람다' '가다' '람다'가 compact
★★★★★★ 。
둘 다 타입이 있기 때문에 TSC는 만족하고 올바른 타입을 얻을 수 있습니다.
Lodash d.ts 파일에서:
/**
* Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are
* falsey.
*
* @param array The array to compact.
* @return Returns the new array of filtered values.
*/
compact<T>(array: List<T | null | undefined | false | "" | 0> | null | undefined): T[];
형식 확인을 통해 필터된 유형과 반품 유형이 다르지 않다는 점만 빼면 모든 것이 정상이라고 생각합니다.
const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = array.filter(f => f !== undefined && f !== null) as any;
console.log(filterdArray);
더 깔끔한 코드와 함께 쉽게 접근할 수 있을 것 같습니다.
const array: (string | null)[] = ['foo', 'bar', null, 'zoo', null];
const filteredArray: string[] = array.filter(a => !!a);
간단히 사용하다
array.filter(Boolean);
이 방법은 모든 진실 값에 적용됩니다.
안타깝게도 유형 추론은 제공하지 않습니다. 이 솔루션은 여기에서 찾을 수 있습니다.
type Truthy<T> = T extends false | '' | 0 | null | undefined ? never : T; //from lodash
function truthy<T>(value: T): value is Truthy<T> {
return Boolean(value); // or !!value
}
const arr =["hello","felow","developer","",null,undefined];
const truthyArr = arr.filter(truthy);
// the type of truthyArr will be string[]
const filterdArray = array.filter(f => !!f) as string[];
새로운 타이프스크립트 기능이나 타이프스크립트 입력으로 해결할 수 있을 것으로 기대하고 있습니다.
여기 제가 지도를 후속 필터와 결합할 때 좋아하는 간단한 방법이 있습니다.
const animals = ['cat', 'dog', 'mouse', 'sheep'];
const notDogAnimals = animals.map(a =>
{
if (a == 'dog')
{
return null!; // just skip dog
}
else {
return { animal: a };
}
}).filter(a => a);
가 걸 될 null!
는 '형'이 .never
늘이 뜻이죠. - 아, 늘이 없다.
이것은 원래 질문과는 약간 다른 질문이지만, 저는 이 시나리오에 자주 참여하기 때문에 다른 메서드 호출을 피하는 데 도움이 됩니다.언젠가 Typescript가 더 나은 방법을 생각해내길 바란다.
을 다른 이 하면 "null"의 이 될 수 .object array
array.filter(x => x != null);
array.filter(x => (x != null) && (x.name == 'Tom'));
하고 TypeScript를 가 몇 .null
추가:
const arrayWithNulls = ["foo", "bar", null, "zoo", null]
type ArrayWithoutNulls = NonNullable<typeof arrayWithNulls[number]>[]
const arrayWithoutNulls = arrayWithNulls.filter(x => x != null) as ArrayWithoutNulls
캐스팅보다 더 합니다.as string[]
이치노
단계별:
- 원래 배열에서 유형을 가져옵니다.
typeof arrayWithNulls[number] // => string | null
null
§:
NonNullable<typeof arrayWithNulls[number]> // => string
- 배열로 만들기:
NonNullable<typeof arrayWithNulls[number]>[] // => string[]
링크:
NonNullable
(공문서)typeof array[number]
(블로그 투고, 공식 문서에서는 아무것도 찾을 수 없었습니다)
「」를 사용합니다.reduce
은 '그러다'를 제시하기도 합니다.reduce
const languages = ["fr", "en", undefined, null, "", "de"]
// the one I prefer:
languages.reduce<string[]>((previous, current) => current ? [...previous, current] : previous, [])
// or
languages.reduce((previous, current) => current ? [...previous, current] : previous, Array<string>())
// or
const reducer = (previous: string[], current: string | undefined | null) => current ? [...previous, current] : previous
languages.reduce(reducer, [])
★★★★★["fr", "en", "de"]
TS Playground는 이쪽입니다.
가장 빠른 방법:
const validData = array.filter(Boolean)
중 및 인터페이스에 대한 할 수 한 후 값을 "할 수 .모듈에 추가한 후 어레이를 "스퀴드"하여 모든 null 값을 제거할 수 있습니다.(any|undefined|null)[]
any[]
.
식으로:mixedArray.squish()
체인과 지도에 좋습니다.
이 코드를 모듈 어딘가에 추가하기만 하면 됩니다(eslint 내용은 생략해도 됩니다만, 여기서 몇 가지 문제가 발생했습니다).
/* eslint-disable no-unused-vars */
/* eslint-disable no-extend-native */
declare global {
interface Array<T> {
squish<NonNull, Nullable extends (NonNull | undefined | null)>(): NonNull[];
}
}
if (!Array.prototype.squish) {
Array.prototype.squish = function squish<NonNull, T extends(NonNull|undefined|null)>
(this: T[]): NonNull[] {
return this.flatMap((e) => (e ? [e] : [])) as NonNull[]
}
}
또는 @p4ck93/ts-is 패키지를 사용해 보십시오.
https://www.npmjs.com/package/ @p4ck493/ts-is
이 예에서는 CDN 메서드를 사용하지만 패키지도 typescript를 지원합니다.
<script>var exports = {};</script>
<script src="//unpkg.com/@p4ck493/ts-is@3.0.1/dist/index.js"></script>
<script>
const {is} = exports;
console.log('is.string: ', is.string('')); // true
console.log('is.string.empty: ', is.string.empty('')); // true
console.log('is.string.not.empty: ', is.string.not.empty('')); // false
const array = ["foo", "bar", null, "zoo", null];
const filterdArray = array.filter(is.string.not.empty);
console.log('array:', array);
console.log('filterdArray:', filterdArray);
</script>
업데이트
또는 TypeScript:
import {is} from '@p4ck493/ts-is';
const array = ["foo", "bar", null, "zoo", null];
const filterdArray = array.filter(is.string.not.empty);
/**
Alternative:
array.filter(is.not.null);
array.filter(is.not.empty);
array.filter(is.string);
**/
수 .map()
고급 솔루션은 Non-Null 아사션 연산자를 사용하고 있습니다.
const array = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = array.filter(s => s != null).map(s => s!);
undefines를 합니다.typeof
및 유형 "" " " " " " " 。Exclude
이치노
const array = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = array
.filter(s => s !== null)
.map(s => s as Exclude<typeof s, null>);
언급URL : https://stackoverflow.com/questions/43118692/typescript-filter-out-nulls-from-an-array
'programing' 카테고리의 다른 글
react에서 .eslintcache 파일을 삭제하는 방법 (0) | 2023.02.23 |
---|---|
Oracle에서 상위 100개 행을 선택하는 방법 (0) | 2023.02.23 |
사이트의 다른 페이지로 WooCommerce 'Shop' 페이지 전달 (0) | 2023.02.23 |
최대 업로드 파일 크기 증가 WordPress 다중 사이트 (0) | 2023.02.23 |
리액트 프로젝트에서 dotenv를 사용할 수 있습니까? (0) | 2023.02.23 |