首页 > 解决方案 > 增加元组数量的函数的打字稿签名

问题描述

是否可以在 Typescript 中为函数编写类型感知声明,它接受元组并返回带有附加项的新函数,而不使用函数重载?

简而言之,我需要表达以下功能:

[T1, T2, ... Tn] + U => [T1, T2, ... Tn, U]

除了使用多个重载之外,还有一种明显的方法:

function append<A, B>(a: [A], b: B): [A, B];
function append<A, B, C>(a: [A, B], c: C): [A, B, C];
function append<A, B, C, D>(a: [A, B, C], d: D): [A, B, C, D];
function append(tuple: any[], b: any): any[] {
  return tuple.concat([b]);
}

有没有办法以以下形式写这个:

function append<T extends any[], U>(t: T, u: U): ??? => ???;

标签: typescriptdependent-type

解决方案


我认为这实际上超出了 Typescript 目前的理解范围。考虑完全没有声明返回类型的函数:

function append<U, T extends any[]>(u: U, ...t: T) {
  return [u, ...t];
}

const a = append(4, 'a', 'b')

常量a显然是 type [number, string, string],但 3.7.2 编译器认为它是一个any[].


推荐阅读