Created
May 16, 2020 00:12
-
-
Save bozdoz/8ff9c04bf37153e4826e268edec61c31 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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