LoginSignup
0
0

More than 1 year has passed since last update.

ts 配列からundefinedを取り除く方法

Last updated at Posted at 2022-12-04

やりたいこと

以下のコードのように filter を使った時、undefinedの型を取り除けないので、取り除けるようにしたい

array.filter((data) => !!data)

方法1(ダメな方法)

以下のように as でアサーションする
この場合、配列自体が undefined のケースを考慮できていない

array.filter((data) => !!data) as string[]]

方法2(良い方法)

Type Guardを使う
こちらは参考にさせていただいたサイトの方法で、配列の型から undefined を除外するのにNonNullable というユーティリティ型を使用しています

array.filter(
    (data): data is NonNullable<typeof data> => !!data
  )

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0