Created
November 23, 2023 13:46
-
-
Save adrienjoly/779abbfd705f3b3a963af395cfa4a9b2 to your computer and use it in GitHub Desktop.
Type guard, so that void/undefined can be excluded from an array's type, after filtering them out, using JSDoc type annotations.
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
/** | |
* Type guard, so that void/undefined can be excluded from an array's type, after filtering them out. | |
* @template T | |
* @param {T | void} val | |
* @returns {val is T} | |
*/ | |
const isDefined = (val) => val && typeof val === 'object' | |
/** @type {number[]} */ | |
const numbers = [-1, 1, 2] | |
/** @type {number[]} */ | |
const numbersAboveZero = numbers | |
.map((n) => n > 0 ? n : undefined) // => ๐ type: (number | undefined)[] | |
.filter(isDefined) // => ๐ type: number[] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment