【发布时间】:2020-03-13 13:38:03
【问题描述】:
我想为下面的这个元组/数组创建一个类型。
这是有效的:
const funcs = [(a: string) => 1, (a: number) => 'A', (a: string) => 2]
这是无效的:
const funcs = [(a: string) => 1, (a: number) => 2, (a: string) => 3]
区别在于中间函数的返回类型从字符串变成了数字。
有可能吗?
type SubtractOne<T extends number> = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62][T];
type AddOne<T extends number> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62][T];
const funcs = [(a: string) => 1, (a: number) => 'A', (a: string) => 2]
type CheckFuncs<T extends any[]> = { [(K extends number) in keyof T]: T[AddOne<K>] }
type funcsType = typeof funcs
type funcsType2 = CheckFuncs<funcsType>
在我的研究过程中,我发现了一种使用映射进行索引的方法。是否可以使用它在 K 中添加或减去 AddOne?那么我可以访问T[K]的ReturnType和Parameter<T[k+1]>[0]?
【问题讨论】:
标签: arrays typescript tuples