zod icon indicating copy to clipboard operation
zod copied to clipboard

New Feature - Variadic tuples with noUncheckedIndexedAccess

Open nicu-chiciuc opened this issue 3 years ago • 1 comments

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
example

and it also correctly types if we want to access some index:

example2

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.

nicu-chiciuc avatar Jul 22 '22 17:07 nicu-chiciuc

I agree, this is a very useful pattern :) https://github.com/colinhacks/zod#nonempty

colinhacks avatar Jul 25 '22 08:07 colinhacks