I have often found myself in a situation where i have an array of objects and I want to transform this into a dictionary of objects. The objects may have a known shape of some sort but they still vary from object to object. What I need is for the resultant object/dictionary to:
- Be type-aware of the discrete properties set on the dictionary
- Know the particulars of each database tables columns/properties
A classic use case is a database's tables. In this case, the dictionary would represent an API for each table and therefore it would maybe share some methods like select
, update
, etc. but the properties which it is operating on are going to vary model by model.
In this case, let's assume an interface of ITableDefinition<T>
as the general definition of each table's API but the generic being the specifics brought in by the underlying table. Now let's say I'm wrapping up all the tables with the following Database()
function:
import { ITableDefinition } from "./Table";
type IDatabase<T extends { [P in keyof T]: T[P] } = any> = {
[P in keyof T]: T[P];
};
function Database(...tables: ITableDefinition<any>[]) {
return {
tables: arrayToObject(tables),
tableNames,
};
}
// provided by @jcalz
function arrayToObject<T extends { name: S }, S extends PropertyKey>(
/** an array of objects */
arr: readonly T[]
) {
return arr.reduce(
(acc, v) => ({ ...acc, [v.name]: v }),
{} as { [V in T as V["name"]]: V }
);
}
The interface ITableDefinition
in the above example is:
import * as t from "io-ts";
export interface ITableDefinition<T extends object> {
name: Readonly<string>;
is: t.Mixed["is"];
encode: t.Mixed["encode"];
decode: t.Mixed["decode"];
select: (cols: keyof T) => string;
update: (record: Partial<T>) => string;
}
As you can see, the tableNames
are successfully returned as an array of strings because every table has a "name" property which is always a string. Sadly, however, tables
is a union type instead of a discriminated union.
Note: this much progress was only achieved with the help of @jcalz invaluable contribution of the
arrayToObject
function.
This problem is avoided when we use test cases with statically typed objects where we can use the as const
TS keywords. This will bring it back to a discriminated union but in our table example this is not possible.
Important:
The answer and insight provided by @jcalz was essential to arrive at a solution but by itself it did not solve the full problem where with the aforementioned Table()
function was producing the objects and henceforth why the use of TS's as const
wasn't an option.
To benefit the community I have posted a fully working solution but most of the heavy lifting/smarts came from @jcalz. If anyone has a more graceful solution in the future I'll be happy to prefer yours over mine.