#StackBounty: #typescript #types Representing function that takes an array of object and returns a single object with a union of all keys

Bounty: 200

I have a function in javascript that takes an array of 0 or more objects of type {string => async fn*(...) => ...} (note the * – they are async generator functions).

The function returns a single object that is a union of the set of all keys in each input object, and the values are async function generators that match the APIs for each input object – the requirement here being that if two input objects share a key, they must also share the function prototype exactly.

For example:

function makeAggregateObject(objects) { ... }

const fish = {
    swim: async function*(distance) { return distance > 10; }, // (number) => boolean
    die: async function*() {} // () => void

const cat = {
    die: async function*() { this.lives -= 1; } // () => void

const human = {
    walk: async function*(steps, hop) { ... } // (number, boolean) => void
    swim: async function*(distance) { return false; } // (number) => boolean

const aggregate = makeAggregateObject([
    human, cat, fish

        swim: async function*(number) => boolean,
        walk: async function*(number, boolean) => void,
        die: async function() => void

As I mentioned earlier, in the case I added e.g. die(number) => boolean to human above, it would be considered an error (of course in Javascript, there’s no way to actually enforce this, but I would like to in Typescript) because the prototype (number) => boolean does not match the previously defined () => void prototypes before it.

Is this even possible in Typescript? How would I go about doing so?

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.