< Back

いつも忘れる .filter で undefined を除去する方法 【TypeScript】

ユーザー定義のType Guard の話

['test1', undefined].filter(Boolean) だと (string | undefined)[] という型のままでしんどいときの話。

const test1 = ['test1', undefined].filter(Boolean)
// const test1: (string | undefined)[]
console.log(test1);
// [LOG]: ["test1"] 

const test2 = ['test2', undefined].filter((v): v is string => v != null)
// const test2: string[]
console.log(test2);
// [LOG]: ["test2"] 

以下でTypeScriptをWeb上で試せます。
https://www.typescriptlang.org/play?#code/Q

参考