Noh | エンジニア向け情報共有コミュニティ
Signup / Login

TSで配列filterしてundefinedを取り除いたときに型からも取り除く方法一覧

y
yosi2025/09/17 1:15

TSで配列filterしてundefinedを取り除いたときに型からも取り除く方法一覧

A
Answerer AIPowered by gpt-4o-mini

TypeScriptで配列をフィルタリングしてundefinedを取り除く際には、いくつかの方法があります。それにより、型からもundefinedを取り除くことができます。以下に代表的な方法をいくつか示します。

1. filterメソッドとアサーションを使う方法

const array: (string | undefined)[] = ['a', undefined, 'b', undefined, 'c']; const filteredArray: string[] = array.filter((item): item is string => item !== undefined);

ここでは、item is stringというユーザー定義ガードを使って、filterの結果の型を明示的にstringにしています。

2. filterメソッドとnon-null assertionを使う方法

const array: (string | undefined)[] = ['a', undefined, 'b', undefined, 'c']; const filteredArray: string[] = array.filter(Boolean) as string[];

Booleanを使ってフィルタリングすることで、undefinednullfalse0などが除外されます。ただし、型の安全性がやや下がります。

3. compact関数を使う(lodashを利用)

lodashのcompact関数を利用することもできます。これにより、undefinednullの要素を簡単に取り除けます。

import { compact } from 'lodash'; const array: (string | undefined)[] = ['a', undefined, 'b', undefined, 'c']; const filteredArray: string[] = compact(array) as string[];

4. 型の条件を使った独自のフィルタ関数

const isDefined = <T>(item: T | undefined): item is T => item !== undefined; const array: (string | undefined)[] = ['a', undefined, 'b', undefined, 'c']; const filteredArray: string[] = array.filter(isDefined);

独自の関数isDefinedを使うことで、undefined以外の要素をフィルタリングし、型を適切に保持できます。

結論

これらの方法を使うことで、TypeScriptにおいて配列からundefinedを取り除き、その型も適切に調整することが可能です。お好みやプロジェクトのニーズに応じて、いずれかの方法を選択してください。

コメントするにはログインが必要です
y
yosi