2

Playground | Sandbox

Let's start at the end with this snapshot which depicts all unit tests passing but highlighted in red, an unfortunate loss of fidelity in types:

enter image description here

What you are seeing is a Configurator() function which provides a way to build up a configuration and when you're done you call done() and the typed configuration is available. The good news is it almost works. It does work at run time (note the blue text which shows that all keys -- a, b, and c -- are indeed set). However, as you see in the circled areas at the bottom, property b is not typed whereas a and c are.

The reason for this miss on typing for b comes from implementation details which are to some degree understood but let's hit them. Here's the Configurator code:

export function Configurator<I extends object>(initial?: I) {
  let configuration = () => initial || {};

  const api = <C extends object>(current: C): IConfigurator<C> => {
    return {
      set<V, K extends string, KV = { [U in K]: V }>(key: K, value: V) {
        const keyValue = ({ [key]: value as V } as unknown) as KV;

        const updated = { ...config, ...keyValue };
        configuration = (): C & KV => updated;

        return api<C & KV>(updated);
      },
      done() {
        return configuration() as C;
      },
    };
  };

  return api(initial || {});
}

The interface IConfigurator<T> is returned on every loop of configuration with the api surface and using set() is able to add in new key value pairs as they come in with full Typescript fidelity. This part works and it is why the variable c remembers the property "a" (see item #1 from above), and why variable d remembers both property "a" (because c knew about it) and property "c".

Property "b" (set on the line highlighted as #2), is remembered at run time because of the configuration parameter being assigned in the Configuration's enclosure versus the api's enclosure. We had originally just assigned in the object value but what you see here is a function which returns a value; we changed this because sometimes Typescript is better at inferring things when a function gets involved. Sadly not here. The configuration type is pegged at being an empty object. Because the api surface as type C we can cast the configuration over to type C but that means that properties like b get orphaned from the type system's inference.

My question is two fold:

  1. Is there a way in which we can capture/remember the type of configuration so that when we call the done() method we can ensure that full type support is available?
  2. Alternatively, if the type for the configuration has been lost is there a way to rebuild it? As you can see from the screenshot, at run time the properties and their types can be identified ... seems like this should lead to a means to achieving full type support but attempts at this so far have failed (see below)

Note: here's the attempt we made to achieve #2 from above.

export type AppendToObject<T, U extends keyof any, V> = {
  [K in keyof T | U]: K extends keyof T ? T[K] : V;
};

/** Given a structured run-time object, iterate over keys and append types */
export const inferObject = <T extends object>(v: T) => {
  let obj = v;

  Object.keys(v).forEach((key) => {
    const value = (v as any)[key];
    obj = fixup(v, key, value);
  });

  return obj;
};

function fixup<V, T extends object, K extends string = string>(obj: T, key: K, value: V) {
  return { ...obj, [key]: value } as AppendToObject<T, K, V>;
}


Note 2: the code for IConfigurator was left out to start and while it will need updating if we find a solution I don't believe it is the root of the problem. None-the-less, I can think of no reason anyone should believe me on this.

interface IConfigurator<C> {
  set<V, K extends string, KV = { [U in K]: V }>(key: K, value: V): IConfigurator<C & KV>;
  done(): C;
}
13
  • It looks like you went to some trouble to make an image of your IDE, but please do not upload images of code/errors when asking a question.
    – jcalz
    Feb 3, 2021 at 20:57
  • 1
    @jcalz why? I have seen other folks respond that way but this isn't instead of code but rather in addition to code and done to help make the problem more clear. There would have been no way to show test and run-time console results nor to highlight certain areas otherwise.
    – ken
    Feb 3, 2021 at 21:00
  • Please consider modifying the above code and image to constitute a minimal reproducible example suitable for dropping into a standalone IDE such as The TypeScript Playground so that others can easily demonstrate the issue for themselves. It is much easier to answer a question when I can start with the problem instead of having to spend effort just to reproduce the problem in the first place.
    – jcalz
    Feb 3, 2021 at 21:00
  • 2
    of course but there was no intent for that to be copied and pasted. pictures are used differently. what you're describing is why pictures should not replace code but in fact all the relevant code has been added as text.
    – ken
    Feb 3, 2021 at 21:18
  • 2
    They DO! Sadly the only way I could prove it to you is take a screenshot. screencast.com/t/uoStvazJt
    – ken
    Feb 3, 2021 at 21:48

2 Answers 2

4

TypeScript doesn't have support for methods that both return a value and narrow the type of the object on which you call the method.

Traditionally (before TS 3.7) I'd say that if you want TypeScript's type checker to keep track of the types properly, you need to use a pure "fluent builder" pattern in which each value in the chain is used exactly once. Or if you do use them multiple times (like your c.set() example), you need to make the methods immutable, so that c.set()'s return value is the only thing affected. Typescript hasn't traditionally been able to capture the idea of an object method mutating the state of its value.

Since TypeScript 3.7 you could use assertion functions to write a configurator where you do the opposite; you ignore the return value of the method, and keep re-using the original object. Each time you call c.set(), it will narrow the type of c.

Your current set() method is intended to do both of those things, but TypeScript can only really support one of those. (And the stateful version has an annoying caveat)


The pure builder version works like this with your existing set() methods:

let o = Configurator()
  .set("a", 5)
  .set("b", "foobar")
  .set("c", { hello: "world" })
  .done();
  
o.a // okay
o.b // okay
o.c // okay

Here we are throwing away every intermediate object after we use it once; we never re-use it.


The stateful approach uses assertion functions as introduced in TypeScript 3.7. These functions allow you to mark void-returning functions as having a narrowing effect on the type of one of their parameters... or in the case of methods, a narrowing effect on the type of the object that has the method. I'm going to change your set() method's signature:

interface IConfigurator<C = {}> {
  add<A extends {}>(dictionary: A): IConfigurator<A & C>;
  set<V, K extends string, KV = { [U in K]: V }>(
    key: K, value: V
  ): asserts this is IConfigurator<C & KV>;
  done(): C;
}

Note the asserts this is... return type. Then you can use the configurator like this:

let c: IConfigurator = Configurator(); 
//   ~~~~~~~~~~~~~~~ <-- note this annotation
c.set("a", 5);
c.set("b", "foobar");
c.set("c", { hello: "world" });

const o = c.done();
o.a // okay
o.b // okay
o.c // okay

Each time c.set() is called, it narrows the type of c, so that when you eventually call c.done(), the return value is known to have all the properties you set on it. Frustratingly, you are required to give an explicit type annotation to c for this to work. If you leave it off, you get an obnoxious error every time you call set() (see microsoft/TypeScript#36931 for more info):

let cBad = Configurator();
cBad.set("a", 5); // error!
//~~~~~~ <-- Assertions require every name in the call target
// to be declared with an explicit type annotation.

Playground link to code

1
  • Even though I didn't ask the original question, this was a very handy read on a side of Typescript I hadn't previously interfaced with. Thanks a lot for taking the time to write this up.
    – Etheryte
    Feb 3, 2021 at 22:17
1

I believe you're running into this issue: Represent the types of function parameters that mutate inside the function.

Sadly I don't think there is an easy fix for it.
I believe that is the reason why most builders start from an already known complete type.

3
  • There are assertion functions, which do this, but they cannot be used painlessly
    – jcalz
    Feb 3, 2021 at 21:50
  • I always start with a fully typed config when I can but in certain cases I have libraries which push the configurator out the consumer of my libraries and then the desire for greater dynamic behavior becomes quite valuable.
    – ken
    Feb 3, 2021 at 22:36
  • Read through the article and that was very helpful to see the last week of my life brought into focus by other's thoughts and desires. Thanks for contributing this.
    – ken
    Feb 3, 2021 at 22:41

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.