Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrienjoly/779abbfd705f3b3a963af395cfa4a9b2 to your computer and use it in GitHub Desktop.
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.
/**
* 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