title: Typing a function based on a JSON schema passed as argument
body: <p>I have a factory function <code>createF</code> that takes as input a JSON schema and outputs a function <code>f</code> that returns object that fits this schema, it looks like:</p>
  <pre><code>const createF = (schema) =&gt; { /* ... */ }
  
  type T1 = number;
  const f1: T1 = createF({
    type: 'integer',
  });
  
  type T2 = {
    a: number;
    b?: string;
    [key: string]: any;
  };
  const f2: T2 = createF({
    type: 'object',
    required: ['a'],
    properties: {
      a: { type: 'number' },
      b: { type: 'string' },
    },
  });
  </code></pre>
  <p><code>f1</code> and <code>f2</code> <em>always</em> return objects that are shaped like <code>T1</code> and <code>T2</code> respectively, but they are not typed: <code>createF</code> is not written so that TS infers the right types to <code>f1</code> and <code>f2</code>. Would that be possible to rewrite <code>createF</code> so that it does? If yes, how?</p>
  <p>I know that it is possible to <a href="https://stackoverflow.com/q/52817922/8186898">have a return type that depends on parameters</a> by using function overloading, but in my case all the possible inputs are all JSON schemas and I don't know how to extend the function overloading solution to this case.</p>
  <p>Currently, I use <a href="https://www.npmjs.com/package/json-schema-to-typescript" rel="nofollow noreferrer">json-schema-to-typescript</a> to generate at compile time types around the functions created by <code>createF</code>, but this is not ideal.</p>
  <hr />
  <p>A bit of context to avoid the <a href="https://meta.stackexchange.com/q/66377/404417">XY problem</a>: I am actually building <a href="https://github.com/ninofiliu/oa-client" rel="nofollow noreferrer">oa-client</a>, a lib that creates a helper based on OpenAPI specs, which contains schemas. At runtime, the created helper only accepts and returns objects defined in the schemas; but on the TS layer there is no types - I have to use the schemas to write TS using node scripts, and that is not ideal, especially since the goal of <a href="https://github.com/ninofiliu/oa-client" rel="nofollow noreferrer">oa-client</a> is to not do code generation.</p>