TypeScript 5.5 にて Array.filter による型の絞り込みがビルトインでサポートされるようになります。 この記事で紹介している例も、 nonNullable に相当するユーザー定義の型ガードがなくても期待する型の絞り込みが行えます。 const arr = [0, 1, 'hello', false, null, undefined]; const result = arr.filter((item) => item != null); // js: [0, 1, 'hello', false] // ts: (string | number | boolean)[] 🎉
![TypeScript で配列から nullable な要素を除去する](https://cdn-ak-scissors.b.st-hatena.com/image/square/8554be998efe73a6e090cb8c8090df499b03eb79/height=288;version=1;width=512/https%3A%2F%2Fres.cloudinary.com%2Fzenn%2Fimage%2Fupload%2Fs--GnRMoQEv--%2Fc_fit%252Cg_north_west%252Cl_text%3Anotosansjp-medium.otf_55%3ATypeScript%252520%2525E3%252581%2525A7%2525E9%252585%25258D%2525E5%252588%252597%2525E3%252581%25258B%2525E3%252582%252589%252520nullable%252520%2525E3%252581%2525AA%2525E8%2525A6%252581%2525E7%2525B4%2525A0%2525E3%252582%252592%2525E9%252599%2525A4%2525E5%25258E%2525BB%2525E3%252581%252599%2525E3%252582%25258B%252Cw_1010%252Cx_90%252Cy_100%2Fg_south_west%252Cl_text%3Anotosansjp-medium.otf_37%3A%2525F0%25259D%252595%2525A4%2525F0%25259D%252595%25259A%2525F0%25259D%252595%25259E%2525F0%25259D%252595%2525A0%2525F0%25259D%252595%252594%2525F0%25259D%252595%252599%2525F0%25259D%252595%252596%2525F0%25259D%252595%252596%252Cx_203%252Cy_121%2Fg_south_west%252Ch_90%252Cl_fetch%3AaHR0cHM6Ly9zdG9yYWdlLmdvb2dsZWFwaXMuY29tL3plbm4tdXNlci11cGxvYWQvYXZhdGFyLzhlOWU3MjdmZDkuanBlZw%3D%3D%252Cr_max%252Cw_90%252Cx_87%252Cy_95%2Fv1627283836%2Fdefault%2Fog-base-w1200-v2.png)