typescript - 打字稿:映射列表类型可能吗?或者我可以更改参数吗通过映射类型?
问题描述
我可以更改 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
解决方案
我终于弄明白了。也许我没有问对我的问题。如果是这种情况,请告诉我。
但这有效:
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
请参阅:打字稿游乐场
推荐阅读
- vb6 - 带有数字格式的VB6错误?
- c# - 服务帐户的 SQL Server 连接字符串
- javascript - 为什么这两个元素定位器调用的行为不同?
- sql-server - 使用多个 LIKE 选项清理查询
- php - laravel 捕获所有路由使 css @import 不起作用
- polymorphism - 强制与“强制多态性”不同吗?
- c# - SelectNodes 未正确拉出所有子节点
- vb.net - MS Access 调用函数通过 VB.NET
- python - 为什么 2019 年我们仍然不能使用 ctypes 从 Python 调用 C++?
- android-studio - Android Studio - 构建命令失败