Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stricter Array Types #2658

Open
samchungy opened this issue Aug 15, 2023 · 2 comments
Open

Stricter Array Types #2658

samchungy opened this issue Aug 15, 2023 · 2 comments

Comments

@samchungy
Copy link
Contributor

samchungy commented Aug 15, 2023

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
Copy link
Contributor Author

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
Copy link

@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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants