如何实现支持可变元组的TypeScript高级函数类型推断?
实现可变长度元组数组的类型推断需求
给定以下TypeScript代码,需要实现foo2函数,使其接受可变长度的元组数组,且每个元组的第二个元素类型能基于自身第一个元素进行类型推断:
type X<T extends string> = `do something here with ${T}` const foo = <const A extends string, B extends X<A>>(tuple: [a: A, b: B]) => tuple foo(['a', `do something here with a`]) // 如何编写foo2,使其接受一个可变长度的元组数组,其中每个元组的第二个元素都能基于第一个元素进行类型推断? foo2([ ['a', `do something here with a`], ['b', `do something here with b`], ['c', `do something here with c`], // ... ])
需求说明
实现一个元组数组,其中每个元组的第二个元素类型依赖于第一个元素类型,且数组内各元组的类型互不影响。
解决方案
通过泛型约束结合const断言,可以实现每个元组独立的类型推断:
type X<T extends string> = `do something here with ${T}` const foo = <const A extends string, B extends X<A>>(tuple: [a: A, b: B]) => tuple foo(['a', `do something here with a`]) // 实现foo2 const foo2 = <const T extends readonly [string, X<string>][]>(arr: T) => arr // 合法调用示例 foo2([ ['a', `do something here with a`], ['b', `do something here with b`], ['c', `do something here with c`] ]) // 错误示例:类型不匹配会触发TypeScript检查 // foo2([['a', `invalid content`]])
原理说明
const泛型参数确保TypeScript保留数组中每个元素的字面量类型,避免类型拓宽为string;readonly [string, X<string>][]约束要求每个元组的第二个元素必须是第一个元素经过X类型转换后的结果;- 数组内每个元组的类型独立推断,互不干扰,完全满足需求。
内容的提问来源于stack exchange,提问作者Jason Kuhrt
相关产品推荐
相关产品推荐

