Browser Data Shapes
URL Query Shape
Browser query strings become small typed records before application code uses them.
URL Query Shape
query.ts
type QueryShape = {
page: number;
filter: string;
};
function readQuery(raw: string): QueryShape {
const pairs: string[] = raw.replace(/^\?/, "").split("&");
const values: Record<string, string> = {};
for (const pair of pairs) {
const [key, value] = pair.split("=");
values[key] = value;
}
return {
page: Number(values.page),
filter: values.filter
};
}
const pageText: string = ;
const rawQuery: string = `?page=${pageText}&filter=active`;
const query: QueryShape = readQuery(rawQuery);
console.log(`${query.filter}:${query.page + 1}`);
type QueryShape = {
page: number;
filter: string;
};
function readQuery(raw: string): QueryShape {
const pairs: string[] = raw.replace(/^\?/, "").split("&");
const values: Record<string, string> = {};
for (const pair of pairs) {
const [key, value] = pair.split("=");
values[key] = value;
}
return {
page: Number(values.page),
filter: values.filter
};
}
const pageText: string = ;
const rawQuery: string = `?page=${pageText}&filter=active`;
const query: QueryShape = readQuery(rawQuery);
console.log(`${query.filter}:${query.page + 1}`);
query record
Parsing a query string into a record separates raw browser text from typed application data.