코딩하다가
Typescript에서 Array.filter로 null 제거시 에러: error TS2322: Type '(A | null)[]' is not assignable to type 'A[]
love-ggoya
2025. 1. 26. 23:29
Array.filter function을 사용하여 배열에서 null 또는 undefined 타입을 제거하려고 하면 아래와 같은 에러를 볼 수 있습니다.
// 예시 코드
const aList: Array<A> = aListWithNulls.filter((a) => a !== null);
// 발생 에러
error TS2322: Type '(A | null)[]' is not assignable to type 'A[]
aListWithNulls 의 타입은 Array<A|null> 인데 aList의 타입은 Array<A>여서 발생하는 에러인데요, 해결 방법은 아래와 같습니다.
// 첫번째 방법: filter 대신에 reduce 사용
// 두번째 방법: 명시적으로 타입 바꿔주기
const aList: Array<A> = aListWithNull.filter((a): a is A => a !== null);
// 세번째 방법: Typescript 버전을 5.5 이상으로 올리기
아래 문서를 확인하면 Typescript 5.5 이상에서는 type prediction이 적용되어 에러가 났던 예시 코드를 그대로 사용할 수 있도록 변경 되었어요.
https://devblogs.microsoft.com/typescript/announcing-typescript-5-5/#inferred-type-predicates
Announcing TypeScript 5.5 - TypeScript
Today we’re excited to announce the release of TypeScript 5.5! If you’re not familiar with TypeScript, it’s a language that builds on top of JavaScript by making it possible to declare and describe types. Writing types in our code allows us to explai
devblogs.microsoft.com