4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【TypeScript】配列から undefined を取り除く

Last updated at Posted at 2021-09-15

使う時忘れる時が多いから、記録しておきます。

// undefined を含む配列
const array: (number | undefined)[] = [1, 2, undefined, 3 , 4];

// データは除外したが、型には undefined が残ったまま
array.filter(item => item !== undefined); // [number | undefined]

// データ、型ともに undefined を除外した
array.filter((item): item is Exclude<typeof item, undefined> => item !== undefined); // [number]
4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?