Devansh Jethmalani Profile picture
Rebellious, Irrational, Untamed. I make softwares, and things that help making them. Sometimes I pen my musings. 22.

Jan 3, 2022, 14 tweets

๐ŸŽ 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.

Keep scrolling