Skip to content

Instantly share code, notes, and snippets.

@bozdoz
Created May 16, 2020 00:12
Show Gist options
  • Save bozdoz/8ff9c04bf37153e4826e268edec61c31 to your computer and use it in GitHub Desktop.
Save bozdoz/8ff9c04bf37153e4826e268edec61c31 to your computer and use it in GitHub Desktop.
/**
* better typing replacement for array method .filter(Boolean)
*
* .filter(Boolean) filters out falsy values, but TypeScript is unaware
* .filter(filterTruthy) does the same but has a type guard.
*
* These examples have identical outputs with differing types
*
* ```
* [1, 2, 0, null].filter(Boolean) // (number | null)[]
* [1, 2, 0, null].filter(filterTruthy) // number[]
* ```
*
*/
const filterTruthy = <T>(value: T): value is Truthy<T> => !!value
type Truthy<T> = T extends false | '' | 0 | null | undefined ? never : T
export default filterTruthy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment