0

I have multiple functions which call each other:

let config;
let callback;

function setConfig(c) {
  config = {};
  for(const i of c.items) config.items[i] = getData(i);
  return {
    setCallback: (cb) => { callback = cb; }
  };
}

x.addEventListener("someEvent", () => callback(config));

// usage

setConfig({items: ["a", "b", "c"]}).setCallback(function myCallback(config) {
  console.log(config.items["a"]);
  console.log(config.items["b"]);
  console.log(config.items["c"]);
})

Is it possible to type this in a way that the c argument of setConfig is generic (depends on the actual config object) and then automatically infer the type of the config argument of myCallback?

I already tried to put the adding of the event listener into the setCallback function, so I could carry around a generic type for setConfig, I would like to do this in another place and also be able to modify config, but still keep the type inferrence.

2
  • 1
    What type are the items supposed to be? What type does getData() return? Commented Jun 29, 2021 at 14:20
  • 1
    Does this work for your needs? If so I'll write up an answer; if not, please elaborate about what's missing or not working. Commented Jun 29, 2021 at 14:25

1 Answer 1

1

The key to getting this to work is Typescript's keyof operator:

interface Config<ConfigItems extends object> {
  items: ConfigItems;
}

type ConfigCallback<ConfigItems extends object> = (
  config: Config<ConfigItems>
) => void;

function setConfig<ConfigItems extends object>(c: {
  items: (keyof ConfigItems)[];
}) {
  config = {
    items: {},
  };

  for (const i of c.items) config.items[i] = getData(i);
  return {
    setCallback: (cb: ConfigCallback<ConfigItems>) => {
      callback = cb;
    },
  };
}

Now, the config argument for myCallback will be inferred as:

Config<{
  a: any;
  b: any;
  c: any;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Also, note that I added the items property when redefining the config object in setConfig

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.