[Typescript] Tips: 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.
import { String, Union } from "ts-toolbelt";
const query = `/home?a=foo&b=wow`;
type Query = typeof query;
type SecondQueryPart = String.Split<Query, "?">[1]; // a=foo&b=wow
type QueryElements = String.Split<SecondQueryPart, "&">;
type QueryParams = {
[QE in QueryElements[number]]: {
[Key in String.Split<QE, "=">[0]]: String.Split<QE, "=">[1];
};
}[QueryElements[number]];
const obj: Union.Merge<QueryParams> = {
a: "foo",
b: "wow"
};