4 ms·
On Reddit the other day, I saw a Typescript (type-safe) implementation of a `get()` function like `get({ a: { b: { c: ['foo'] } } }, "a.b.c[0]") === 'foo'` usin
by hombre_fatal 6y ago
On Reddit the other day, I saw a Typescript (type-safe) implementation of a `get()` function like `get({ a: { b: { c: ['foo'] } } }, "a.b.c[0]") === 'foo'` using recursive string templates in the type definition.
e.g. get({ name: 'Toby' }, "name.prop1.prop2") would fail as you're trying to call .prop1 on a string.
Really blew my mind. I'm used to having to give up simple APIs like that when moving to a statically-typed language.
- lmm 6y agoYou might see if your language supports lenses - a lot of ML-like languages can do something like: get({ a: { b: { c: ['foo'] } } }, a *> b *> c *> _0) and a macro to unfold the lens from a literal string is probably something that exists as well.
- neurotrace 6y agoI like monocle-ts for lenses in TS https://github.com/gcanti/monocle-ts https://github.com/gcanti/monocle-ts
- iamuser7 6y agoAlso see Immer Js https://github.com/immerjs/immer https://github.com/immerjs/immer
- hombre_fatal 6y agoFor sure. I just think that sort of string API is a great example of something we've historically had to trade off for type-safety. There are of course nice qualities of simple functional composition and custom operators, though it comes with another layer of overhead that you wouldn't necessarily always choose over a simpler API in every case. Richer typed expressiveness lets us pick the right trade-off without being forced.
- lmm 6y agoMy point is that it's something a lot of statically-typed languages have been able to do for a while - the classic lens paper/talk is about 10 years old at this point, and the literal-type support that you'd need to convert a string to a typesafe lens has been around for a pretty similar length of time at least in some places.