With variadic tuple types Typescript allows me to define generic Types that isolate Parts from a tuple type.
For the sake of simplicity in this question, let us just talk about splitting the first length-1 elements and the last:
type Head<T extends any[]> = T extends [ ...infer Head, any ] ? Head : any[];
Now assume I have some typed tuple instance and want to get both
- the first
length - 1elements and - the last element
const args: [...T, D] // assume I have that in a context where T and D exist
const last: D = args[-1] // this works just fine
const head: T = args.slice(0, -1) // this does not - I have to cast as unknown as T
Is there a way to get the head properly typed without having to cast?
You could declare some helper functions for your problem:
playground