我有一个联合类型的函数:

function Function1(arg0: string, arg1: any[], name: "hello" | "bye") {
  return name;
}

function Function2(arg0: string, arg1: any[], name: "foo" | "bar") {
  return name;
}


type Functions = typeof Function1 | typeof Function2;

现在我想创建一个类型,它接受一个元组,其中第一个位置是实际函数,第二个位置是相应的"name"参数.


const baz = [Function1, "foo"];

我试过这个:

type FooBar<T = Functions> = [T, Parameters<T>[2]];

首先,它给出一个错误Parameters<T>[2]"类型‘T’不满足约束‘(...args:any)=&gt;any’" "

它几乎可以工作,但我从两个函数中获得了所有参数.

推荐答案

你想要distribute你的[T, Parameters<T>[0]]运算超过Tunions,所以我们可以写一个distributive conditional type来做到这一点.让我们来介绍一下实用程序类型:

type FuncThirdArgTuple<T> = 
  T extends (a1: any, a2: any, a3: infer A) => any ? [T, A] : never

它不使用Parameters<T>[2],而是直接使用infer来获取第三个参数类型.

如果我们将它应用于Functions,我们得到:

type FuncThirdArgTupleForFunctions = FuncThirdArgTuple<Functions>
/* type FuncThirdArgTupleForFunctions = 
    [
      (arg0: string, arg1: any[], name: "hello" | "bye") => "hello" | "bye", 
      "hello" | "bye"
    ] | [
      (arg0: string, arg1: any[], name: "foo" | "bar") => "foo" | "bar", 
      "foo" | "bar"
    ]
*/

看起来像是你想要的类型.让我们来测试一下:

let baz: FuncThirdArgTupleForFunctions;
baz = [function1, "hello"]; // okay
baz = [function1, "foo"]; // error

看上go 不错.

Playground link to code

Typescript相关问答推荐

Angular 过滤器形式基于某些条件的数组控制

如何使用Zod使一个基于其他字段值的字段为必填字段?

访问继承接口的属性时在html中出错.角形

如何将泛型对象作为返回类型添加到类型脚本中

我可以以这样一种方式键入对象,只允许它的键作为它的值吗?

如何在Type脚本中动态扩展函数的参数类型?

推断从其他类型派生的类型

如何在typescript中为this关键字设置上下文

刷新时保持当前名称的Angular

使用泛型识别对象值类型

tailwind css未被应用-react

TS2739将接口类型变量赋值给具体变量

map 未显示控制台未显示任何错误@reaction-google-map/api

如何正确地将元组表格输入到对象数组实用函数(如ZIP)中,避免在TypeScrip 5.2.2中合并所有值

创建一个函数,该函数返回一个行为方式与传入函数相同的函数

为什么TypeScrip假定{...省略类型,缺少类型,...选取类型,添加&>}为省略类型,缺少类型?

为什么受歧视的unions 在一种情况下运作良好,但在另一种非常类似的情况下却不起作用?

确保财产存在

为什么 Typescript 无法正确推断数组元素的类型?

是否可以使用元组中对象的键来映射类型