首页 > 解决方案 > 打字稿:映射列表类型可能吗?或者我可以更改参数吗通过映射类型?

问题描述

我可以更改 Typescript 数组类型中的类型类型吗?

代码示例:

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

解决方案


我终于弄明白了。也许我没有问对我的问题。如果是这种情况,请告诉我。

但这有效:

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

请参阅:打字稿游乐场


推荐阅读