Typescript: Are mapped list types possible? Or can I change the Parameters<Func> Types via mapping?

0

Issue

Can I change the type of the types within a Typescript array type?

Code example:

const func1 = (x1: string, x2: string) => '${x1} + ${x2}';
const func2 = (x1: number, x2: number) => x1 + x2;

// i need sth like this 
// type Mapper<Type> = Array<Array<Property> keyof Type>;
// so that i can do this
// Mapper<Parameters<Fn>>

function callFunction<Fn extends (...args: any[]) => string | number>(func: Fn, ...params: Parameters<Fn>) {
  // do sth, example:
  const inputs = params.map(item => item[0]);
  func(...inputs);
}

callFunction(func1, ['1'], ['1']);  // and then there should be no error here
callFunction(func2, [1], [1]);  // and no error here

Typescript Playground

Solution

I finally figured it out. Maybe I didn’t ask my question right. If that was the case just let me know.

But this works:

const func1 = (x1: string, x2: string) => '${x1} + ${x2}';
const func2 = (x1: number, x2: number) => x1 + x2;
const func3 = (x1: string, x2: number) => x1 + x2;

type Mapper<T> = T extends (infer U)[] ? U[][] : never;

function callFunction<Fn extends (...args: any[]) => string | number>
  (func: Fn, ...params: Mapper<Parameters<Fn>>) 
{
  // do sth, example:
  const inputs = params.map(item => item[0]);
  func(...inputs);
}

callFunction(func1, ['1'], ['1']);  // no error here
callFunction(func2, [1], [1]);  // no error here
callFunction(func3, ['1'], ['1']);  // error here would be nice but it's fine like that

See: Typescript Playground

Answered By – danielmoessner

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More