首页 > 解决方案 > 使用 TypeScript 中的对象列表中的参数执行函数

问题描述

我有一个包含 type 元素的列表{ funcToExecute: (arg: U) => void; input: U }。我希望在 usingforEach和适当的输入中执行函数。我的问题是 的参数funcToExecute可以是不同的类型。考虑这个例子:

const functionA = (arg: number) => {
  console.log(arg + 2);
};

const functionB = (arg: string) => {
  console.log(parseInt(arg) + 2);
};

const foo = [
  { funcToExecute: functionA, input: 12 },
  { funcToExecute: functionB, input: `12` },
];

foo.forEach(e => e.funcToExecute(e.input)); // error: 'string | number' is not assignable to never

我可以通过使用这样的东西绕过类型系统:

type functionWithInput<U> = {
  funcToExecute: (arg: U) => void;
  input: U;
};

foo.forEach((e: functionWithInput<any>) => e.funcToExecute(e.input)); // ok, but not type safe

我的问题有一个优雅的解决方案吗?

标签: typescript

解决方案


推荐阅读