
Welcome to a deep dive into an impressive demonstration of TypeScript's advanced types and the utility library, ts-toolbelt. The objective of this article is to explore a TypeScript script that generates IntelliSense auto-completion for URL query parameters. Let's break down each code segment to understand its function better.
Importing Utilities#
import { String, Union } from "ts-toolbelt";
The initial line imports utility functions from the ts-toolbelt package. This library offers valuable utilities to harness TypeScript's potential powerfully, thereby providing solutions to develop more robust and dynamic scripts.
Defining URL Query#
const query = /home?a=foo&b=bar;
type Query = typeof query;
The script begins by defining a string, query, representing our URL. It then employs TypeScript's typeof operator to derive a type from query. Essentially, Query becomes a type related to the content stored in query.
Extracting Query Parameters#
type SecondaryQueryPart = String.Split<Query, "?">[1];
In this particular section, the String.Split function of ts-toolbelt splits the URL at the "?" character, generating an array of substrings. Index [1] retrieves the substring following "?", which embodies the actual query parameters.
Splitting Individual Parameters#
type QueryElements = String.Split<SecondaryQueryPart, "&">;
Taking things further, the resultant query string undergoes another split operation using the "&" character. Consequently, it isolates individual query parameters, returning them as an array of strings.
Creating Query Parameter Type Map#
type QueryParams = {
[QueryElement in QueryElements[number]]: {
[key in String.Split<QueryElement, "=">[0]]: String.Split<
QueryElement,
"="
>[1];
};
}[QueryElements[number]];
This intricate segment constructs a new type, QueryParams, representing key-value pairs in the query string. It cycles through each QueryElement from the QueryElements type, splits it around "=", and forms a new record type with these keys and corresponding values.
In essence, it's creating a map of parameter types, thereby enabling subsequent code to understand what type each parameter should be.
Building Final Object#
const obj: Union.Merge = {
a: "foo",
b: "bar",
};
Lastly, an object obj is defined with a type Union.Merge, another utility from ts-toolbelt. This function merges intersecting types into a single type. Therefore, obj epitomizes an object with inferred types from specific URL query parameters, offering intelligent auto-complete suggestions as we manipulate it.
Conclusion#
In summary, this TypeScript script beautifully demonstrates how we can create a method to infer keys and potential values for URL parameters from given URLs, enriching the typing experience in TypeScript. Such smart usage of TypeScript's advanced types and utility libraries like ts-toolbelt manifests the power of modern JavaScript ecosystems in building complex, but easily maintainable software architecture.
Source: typescript-101/Advanced/day7