Decode URL search params at the type level with ts-toolbelt

TypeScript's string interpolation powers are incredible, especially since 4.1. Add some utilities from ts-toolbelt, and you've got a stew going.

Here, we decode some URL search params AT THE TYPE LEVEL.

Discuss on Twitter

Transcript

Hello folks. Today I'm going to show you how cool TypeScript's string interpolation powers really are. We want to turn this query here, this kind of search params query into an object down here. Through this crazy web of TypeScripts, we managed to do it.

Here we should see that if we go a=wonderful, then the type down here is no longer correct. It gives us auto complete to wonderful. Let's go through each step and see how we've managed to do this. First of all, we've taken the query and just for fun purposes, we've taken a type of it. We're going to type of query.

Next up, the second query part we've basically split the query by here and we've taken the second part of it. If I remove the second part here, we've got string query part. We've split it by this point here. We've just said just grab the second bit of it.

Now we've split it again by the & here. We've got now a=wonderful and B=now. We are doing this by grabbing some utilities from TS tool belt, which is a very cool library. Next up, we've got these query params, which somehow we've managed to turn into a union type. We've got now a=wonderful and b=now.

What we do is we take query elements, which is a two pull here and we say, first of all, we want each query element. The query elements number here is a way of saying each one of these query elements. For each query element in that two pull, first of all we grab the key here.

That key is going to be the a for instance, there, so a=wonderful because we're splitting the string by the by the equals there and grabbing the first part, and then we say is the value. The value is then the same code there is we're grabbing the second part.

We then do this funny thing that we've seen in previous tips, where we then iterate over each member of that object. If we return this or grab it there, then you'd see it would be a=wonderful, b=now. Like this, for instance.

Whereas instead we grab that and we do that instead, and that means that we then just get a=wonderful, b=now. Then we union merge them, which is just merges all the elements of the union into an object.

More Tips