Skip to content

Instantly share code, notes, and snippets.

@codeandcats
Last active July 8, 2021 05:19
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 codeandcats/e25799ec9358bfe0671b07892c9c48d1 to your computer and use it in GitHub Desktop.
Save codeandcats/e25799ec9358bfe0671b07892c9c48d1 to your computer and use it in GitHub Desktop.
Array.filter(Boolean)
declare global {
interface Array<T> {
filter(predicate: typeof Boolean): Exclude<T, undefined | null | false | 0 | ''>[]
}
}
export default global
type Person = {
name: string;
}
const people = [{ name: 'alice' }, null, { name: 'bob' }];
people.filter(() => 1).forEach(person => console.log(person.name)); // With StrictNullChecks enabled, compiler rightfully errors, knowing person can be null
people.filter(Boolean).forEach(person => console.log(person.name)); // Even with StrictNullChecks enabled, compiler is now cool, knowing person cannot be null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment