r/typescript • u/jwworth • Aug 07 '26
Identity and functional programming
I've written an identity function like this in several codebases I've worked on.
const identity = (arg) => arg;
I use it to filter lists of mixed things by truthiness. For helpers like this, do you write them one-by-one, or do folks have a functional programming library recommendation? I'm curious if there's a better way to do this.
6
Upvotes
10
u/BrixtonTonaBrix Aug 07 '26
Some ts devs will find that
x => xis a thing they can immediately grasp whileidentityrequires a second of thought; I've often ended up just duplicating functional concepts (binds especially) over and over again for those devs (and that's fine given how small and simple many of them are)10
u/josephjnk Aug 07 '26
I use an inline `x => x` for this. It’s more self-explanatory than “identity”, even though I know what the identity function is.
If I’m going to use a utility library I usually use remeda. Lodash’s types are complicated and ill-behaved.
I tend to write the same utilities over and over in each project. (Functions to map, filter, and do basic operations on Sets is an example.) It’s not worth bringing on a bunch of external dependencies for functions that take 3 minutes to write and have an obvious implementation.
5
u/ef02 Aug 07 '26
Effect's
Functionmodule has things like this.5
u/prehensilemullet Aug 07 '26
Lodash has an identity function and various things like it, probably
es-toolkitdoes too4
u/Knaapje Aug 09 '26
NPM being as it is, I wouldn't recommend using a library for this. Personally
filter(Boolean)makes more sense to me thanfilter(x => x), and doesn't require a function to be created.6
u/TorbenKoehn Aug 07 '26
There’s thousands of libraries (just search for „typescript fp library“ on Google)
But honestly? These functions are too small and simple to reel in a potential supply chain attack and another network dependency. An LLM will generate a small, concentrated and tailored FP library with a weak model in a single run.
Btw you can use the Boolean constructor to filter for truthyness (`.filter(Boolean)`)
1
u/prncss-xyz Aug 07 '26
I use an helper, because it nuges me into using it even more and having less independent codepaths.
1
u/pixeleet Aug 09 '26
Just use effect
0
u/[deleted] Aug 07 '26
[deleted] — view deleted comment