1

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:

  1. Be type-aware of the discrete properties set on the dictionary
  2. 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.

2 Answers 2

2

You'll definitely need to use type assertions or the like to convince the compiler that reduce() will return a value of the type you desire, since the compiler won't be able to automatically follow the concept of "copy the name property from each element of the array to a key".

As for which type you desire, here's one possibility:

function arrayToObj<
    T extends { name: S }, S extends PropertyKey
>(arr: readonly T[]) {
    return arr.reduce(
        (acc, v) => ({ ...acc, [v.name]: v }),
        {} as { [V in T as V["name"]]: V }
    );
}

We are saying that the arr input to arrayToObj() is of type readonly T[] for some generic type T that has a key-like name property.

In a perfect world you could just say T extends {name: PropertyKey} and be done with it, but unfortunately this will usually cause the compiler to infer a wide type like string for the name property when you call arrayToObj(). But that won't work for you; you need actual literal keys. So I introduce a new type parameter S extends PropertyKey and use that as the name property. This seemingly extraneous parameter serves to give the compiler a hint that we want literal names if possible. Yes, it's black magic. See microsoft/TypeScript#30680 for a feature request to allow for a less arcane way to do such hinting.

Anyway, the output type is { [V in T as V["name"]]: V }. This is using key remapping in mapped types as introduced in TypeScript 4.1 to say "for each element value V in the full union of element values T in the arr array, we want a key of type V["name"].


Let's try it out:

const obj = arrayToObj([
    { name: "foo", val: 123 },
    { name: "bar", val: "bar" },
    { name: "baz", val: new Date() }
]);
/* const obj: {
    foo: {
        name: "foo";
        val: number;
    };
    bar: {
        name: "bar";
        val: string;
    };
    baz: {
        name: "baz";
        val: Date;
    };
} */

console.log(obj.foo.val.toFixed(2)); // 123.00
console.log(obj.bar.val.toUpperCase()); // BAR
console.log(obj.baz.val.getFullYear()); // 2021

Looks good. The implementation and the compiler agree about the type of obj.

Playground link to code

14
  • this might improve things a bit but it fails to achieve what I'm aiming for in two important ways. Most importantly for my use case is that I'm able to export the object to a consumer and they will then be able to auto-complete the names of the tables but still have no type support on the dictionary so the user is not told what tables exist and can choose any string name they like. Screenshot.
    – ken
    Feb 10, 2021 at 19:41
  • the second issue is that while your tests print the right results at run-time, they would need type guards to transpile in TS as the "value" property in your tests are simple union types not discriminiated unions. Screenshot.
    – ken
    Feb 10, 2021 at 19:41
  • there is a third issue as well -- which may be better left as a separate matter -- but inference which works on the original object is lost when the object leverages generics. Screenshot.
    – ken
    Feb 10, 2021 at 19:42
  • it is clear the force is very strong with you in TS so maybe what I'm hitting is a real limit of TS? I hope not but I can't find any ways forward here and my time budget is running out. I have updated the repo with your translation function and added further tests. If you have any further ideas I remain keenly interested.
    – ken
    Feb 10, 2021 at 19:42
  • 1
    I understand, and I'm sorry my example wasn't minimal enough. Believe it or not, i created this repo for this purpose. The actual repo is private and much more complex.
    – ken
    Feb 10, 2021 at 21:37
0

The first step we must take is to change the ITableDefinition interface to take a second generic type S:

export interface ITableDefinition<T extends object, S> {
  name: S;

  is: t.Mixed["is"];
  encode: t.Mixed["encode"];
  decode: t.Mixed["decode"];

  select: (cols: keyof T) => string;
  update: (record: Partial<T>) => string;
}

And then we must also change our signature of the Table function to:

export const Table = <
  T extends { name: Readonly<string> },
  S extends T["name"] = T["name"]
>(
  model: t.Type<T>
): Readonly<ITableDefinition<T, S>> => {
  return {
    // basics
    name: model.name as S,
    // io-ts
    is: model.is,
    encode: model.encode,
    decode: model.decode,
    // CRUD
    select: (cols) => `this is just a test`,
    update: (record) => `this is just a test`,
  };
};

This allows us to infer S for each call and to Table and thereby ensure that the "name" property is a literal type and not just the generic string type. Already examples like the following result in a discriminated union (and thereby strong typing):

const tables = arrayToObject(Table(Song), Table(Playlist));
expect(result.Song.name).toBe("Song");
expect(result.Playlist.name).toBe("Playlist");
// this one shows that the select() method understands the distinct
// columns on our Song table.
expect(result.Song.select("artist")).toBe("this is just a test");

This is great but in our original problem we talked about a small wrapper function called Database(). To make this behave in its most basic form we can do this:

export function Database<T extends ITableDefinition<any, S>, S extends PropertyKey>(
  tbls: readonly T[]
) {
  return {
    tables: arrayToObject(tbls),
    tableNames: tbls.map((table) => table.name),
  };
}

Note: the original problem had a destructured tables input to Database and at least at first blush it would appear this destructuring throws TS off enough that the dark arts we're using no longer work. From my standpoint the API looks kinda cooler destructured but it's not a hill i'm willing to die on.

All code in this working answer can be found in the answer branch of the same repo referred to in the question. The link is below:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.