Can a new type be created for the given tuple/array that has certain validation constraints?
The following array is considered valid:
const funcs = [(a: string) => 1, (a: number) => 'A', (a: string) => 2]
However, this one is invalid due to a change in return types:
const funcs = [(a: string) => 1, (a: number) => 2, (a: string) => 3]
The key difference is the return type of the middle function being modified from string to number.
Is there a way to achieve this through TypeScript?
type SubtractOne<T extends number> = [-1, 0, 1, 2, ...][T];
type AddOne<T extends number> = [1, 2, 3, 4, ...][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>
A potential solution involves indexing with mapping. Could this method be applied to perform addition or subtraction using AddOne
on K? This would enable access to the ReturnType
of T[K]
and the Parameter<T[k+1]>[0]
.