zod
zod copied to clipboard
New Feature - Variadic tuples with noUncheckedIndexedAccess
Variadic tuples were introduced in Typescript 4.0, and they allow some pretty nifty tricks. If the --noUncheckedIndexedAccess is enabled, it's possible to differentiate arrays that are guaranteed to have at least one element from simple arrays, like so:
type Array1<T> = [T, ...T[]];
const a: Array1<string> = []; // this will show an error
const b: string[] = []; // no error here
and it also correctly types if we want to access some index:
I used this approach in a previous project, but had to define manually all the necessary type guards to check if a standard array has at least one element.
https://github.com/nicu-chiciuc/dependent-ts/blob/59f92dc243bfdc53494fd6e3dfd13efbef026829/src/index.ts#L82
I was wondering if this is something that would be of interest to somebody.
I agree, this is a very useful pattern :) https://github.com/colinhacks/zod#nonempty