colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
32.83k stars 1.14k forks source link

Stricter Array Types #2658

Open samchungy opened 1 year ago

samchungy commented 1 year ago

Hey crew!

We rely on noUncheckedIndexedAccess on our repos so we rely on nonempty array types.

image

This makes enforcing array type lengths very important.

This proposes enhancements to min and length checks to create even more accurate types which can work well with noUncheckedIndexedAccess.

z.string().min(3);
// [string, string, string, ...string[]];

z.string().length(3);
// [string, string, string];

We could type the following


type MaxArray<
  T,
  Max extends number,
  Min extends number = 0,
  R extends T[] = Tuple<T, Max>
> = R["length"] extends Min
  ? Min extends 0
    ? []
    : never
  : R extends [infer U, ...infer V]
  ? U extends undefined
    ? never
    : V extends T[]
    ? R | MaxArray<T, Max, Min, V>
    : never
  : never;

z.string().max(3);
// [] | [string] | [string, string] | [string, string, string];

But that would require a little bit of rework to pipe min and max cardinality around and probably isn't all that helpful in general.

samchungy commented 1 year ago

If this isn't desirable I can hide the type changes behind .nonempty() eg. When you use .nonempty() and .min() it will produce the stricter type

damian-balas commented 11 months ago

@samchungy Any progress on this?

I need this type

type TypeINeed = [number, number];
type TypeItProduces = [number, ...number[]];

I've used this methonds, but none returned infered type as: [number,number]

{
  rooms: z.array(z.number()).nonempty().min(2).max(2).length(2),
  rooms: z.number().array().min(2).nonempty(),
  rooms: z.number().array().min(2).max(2).nonempty(),
}

Is there a way in the current version?