typescript - 使用 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
我的问题有一个优雅的解决方案吗?
解决方案
推荐阅读
- excel - 复制活动行并在下面插入,即使使用活动过滤器
- r - 使用 lapply 的矩阵子集列表
- c++ - 从 std::cout 理解 operator<<()
- liferay - 可以在数据库中访问创建的用户资源的 Liferay 自定义字段吗?
- python - 如何创建一个不是类型实例的类?
- entity-framework-core - 如何使用实体框架工作核心中的资源来制作多语言应用程序?
- r - R 使用 timeSeries::timeSeries()
- kubernetes - 使用分子和 kubernetes 建立基础设施(怀疑)
- hadoop - 更改区域数时的 Hbase 行键加盐
- bcpl - 如何在 MacOS 或 Linux 下运行 BCPL