๐ New Year's Gift for Y'all
โ `@โsthir/predicate` โ An eDSL to write typed predicates
๐ง๐ปโโ๏ธ Write your logical expression in a JS-like eDSL and get the typed predicate inferred.
๐
๐๐ป Let me explain...github.com/devanshj/sthirโฆ
We often write predicates, for example while filtering an array. But its type (as in `x is NarrowedX`) doesn't get inferred...
Moreover TypeScript is a little conservative, if you were writing this in JavaScript you won't write `"a" in x`, you'd simply write `typeof x.a === "string"`, wouldn't you?
With `@โsthir/predicate` you can simply import `p` and write the predicate...
๐๐ปโโ๏ธ in JS-like DSL
๐ช๐ป with autocompletions
๐ฅต and the typed predicate gets inferred automatically!
๐๐ป Try it yourself tsplay.dev/wEGZgm
And you know what's the best part? With you can use the macro version `@โsthir/predicate/macro` with `babel-plugin-macro` (thanks to @kentcdodds) for zero runtime overhead.
If you use the macro version in the above code, it'll get transformed to this in build-time! ๐ค
You can also use the predicate in any other places that affect the control-flow analysis, for example in an `if` statement...
And that too would be inlined with the macro
tsplay.dev/mZbkJm
And I see ya'll get bummed here on twitter when TypeScript doesn't infer the predicate and doesn't narrow the types. Let's look at a few examples and see how `@โsthir/predicate` fixes it ๐๐ป
๐ค Problem: x.com/wcandillon/staโฆ
๐ Solved: tsplay.dev/NddqyN
Now there is such a library, @wcandillon ๐
๐ค Problem: x.com/addaleax/statuโฆ
๐ Solved: tsplay.dev/NVgGvm
@addaleax I hope this makes you love TS even more! ๐
๐ค Problem: x.com/AdamRackis/staโฆ
๐ Solved: tsplay.dev/w2EJYW
There you go @AdamRackis (not stupid for asking that question but still stupid for thinking it was a great decision to make `Promise` non-monadic ๐)
That's it folks, enjoy!
If you think `@โsthir/predicate` is dope, don't forget to RT to share it with your friends ๐คช
cc @typescript @drosenwasser @SeaRyanC Next time someone complains about not inferring typed predicates send them here ๐๐ป๐๐
Also I forgot to pitch how `@โsthir/predicate` makes your code more type-safe than the code that doesn't use it ๐๐ป๐ฎ๐ปโโ๏ธ
@threadreaderapp unroll
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.