Last active
July 8, 2021 05:19
-
-
Save codeandcats/e25799ec9358bfe0671b07892c9c48d1 to your computer and use it in GitHub Desktop.
Array.filter(Boolean)
This file contains 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
declare global { | |
interface Array<T> { | |
filter(predicate: typeof Boolean): Exclude<T, undefined | null | false | 0 | ''>[] | |
} | |
} | |
export default global |
This file contains 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 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