Skip to content

Instantly share code, notes, and snippets.

@stern-shawn
Created January 27, 2021 02:13
Show Gist options
  • Save stern-shawn/2d517df61858f890b55d31bf85441c6d to your computer and use it in GitHub Desktop.
Save stern-shawn/2d517df61858f890b55d31bf85441c6d to your computer and use it in GitHub Desktop.
Enable typesafe arr.shift() inside of an if check for if(arr.length) { arr.shift() }
export const isShiftable = <T>(arr: T[]): arr is { shift(): T } & Array<T> => arr.length > 0;
@stern-shawn
Copy link
Author

stern-shawn commented Jan 27, 2021

Helps to counter this sheer annoyance:

// In the context of a NodeJS Read Stream...
if (this.readSource.length > 0) {
  return this.push(this.readSource.shift()); // Error, cannot push undefined. Typed as 'T | undefined' instead of 'T' (only makes sense if array is sparse 😐 )
}

to this

if (isShiftable(this.readSource)) {
  return this.push(this.readSource.shift()); // Typed as 'T', no errors!
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment