首页 > 其他分享 >[Typescript] Tips: Decode URL search params at the type level with ts-toolbelt

[Typescript] Tips: Decode URL search params at the type level with ts-toolbelt

时间:2022-09-28 21:44:06浏览次数:96  
标签:search Typescript String level wow toolbelt ts Split type

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

 

标签:search,Typescript,String,level,wow,toolbelt,ts,Split,type
From: https://www.cnblogs.com/Answer1215/p/16739674.html

相关文章