-1

So now that typescript 4 is out I expected this to be easier but I still have not found a way to accomplish this.

I am trying to make a function that takes in a tuple containing a specific Generic and returns a Generic returning containing the values.

interface STORE<T> {
  data: T;
}

const merge = <U extends any, T extends readonly STORE<U>[]>(values: T): STORE<U[]> =>
  values.reduce<STORE<U[]>>(
    (acc, item) => {
      return { data: [...acc.data, item.data] };
    },
    { data: [] },
  );

for example calling this should result in the following

assert(merge([{ data: 'test' }, { data: 2 }]), { data: ['test', 2]});

This however will return the value as STORE<unknown[]> instead of maintaining the type from the input.

ZNackasha
  • 755
  • 2
  • 9
  • 29
  • 2
    Please publish full example in TS playground – captain-yossarian from Ukraine Sep 29 '20 at 14:49
  • 1
    Without a [mcve] including at least toy definitions for `TYPEONE` and `TYPETWO` it's hard to answer this. The right answer is likely to be using just one type parameter in the function, but I'm not able to verify anything without a reproducible example here. – jcalz Sep 29 '20 at 15:21
  • @captain-yossarian i have updated the question to provide and example – ZNackasha Sep 29 '20 at 21:52
  • @jcalz i have updated the question to provide and example – ZNackasha Sep 29 '20 at 23:04
  • I think these answers might be helpful for you: 1) https://stackoverflow.com/questions/63325817/typescript-return-type-of-unknown-merge-of-objects/63326167#63326167 2) https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type/50375286#50375286 – captain-yossarian from Ukraine Sep 30 '20 at 08:52

1 Answers1

0

see why does typescript function parameter type infer failed?

By using T & (constraint of T) may solve your problem:

const merge = <U extends any, T extends readonly STORE<U>[]>(
  values: T & readonly STORE<U>[],
         // ^ here to ---- here ^
): STORE<U[]> => values.reduce<STORE<U[]>>((acc, item) => {
    return {data: [...acc.data, item.data]};  
  }, {data: []})


interface STORE<T> {
  data: T;
}
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59
  • this does not work with the example above i simply get `Type 'number' is not assignable to type 'string'.ts(2322)` on the second entry in the array. – ZNackasha Sep 29 '20 at 22:15