typescript - 增加元组数量的函数的打字稿签名
问题描述
是否可以在 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): ??? => ???;
解决方案
我认为这实际上超出了 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[]
.
推荐阅读
- gatsby - Gatsby v1 和 netlify 持续集成
- reactjs - 将 React 页面解析为字符串
- angular - 在 authGaurd 中以角度获取未定义的对象
- mysql - 让认证用户进入 vuejs 对象
- go - 安装 golang.org/x/tools/cmd/guru 错误
- c# - 检测列重新排序 - ColumnDisplayIndexChanged 多次引发
- laravel - 别名的命名空间在哪里定义?
- javascript - 延迟后如何显示模态?
- android - kotlin android中带有注释的抽象val
- laravel - 当我在 laravel 中发送邮件时出现错误