Skip to content

Instantly share code, notes, and snippets.

@codeandcats
Last active October 16, 2025 06:49
Show Gist options
  • Select an option

  • Save codeandcats/e25799ec9358bfe0671b07892c9c48d1 to your computer and use it in GitHub Desktop.

Select an option

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
@codeandcats
Copy link
Author

These days I would just add the ts-reset module which includes this and other niceties.

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