[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"
};

 

posted @ 2022-09-28 21:37  Zhentiw  阅读(43)  评论(0编辑  收藏  举报