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

size on array uses a permissive type #1184

Open
shellscape opened this issue Jun 10, 2023 · 0 comments
Open

size on array uses a permissive type #1184

shellscape opened this issue Jun 10, 2023 · 0 comments

Comments

@shellscape
Copy link

Consider the following:

const ActionWildcardStruct = size(array(literal('*')), 1);
export type ActionWildcard = Infer<typeof ActionWildcardStruct>;

That Infer produces a type of type ActionWildcard = "*"[]. While that's correct, it's overly permissive given the size constraints. Instead, we could use something like this:

// Lifted from: https://stackoverflow.com/questions/41139763/how-to-declare-a-fixed-length-array-in-typescript
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number;
type ArrayItems<T extends any[]> = T extends Array<infer TItems> ? TItems : never;
type FixedLengthArray<T extends any[]> = Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>> & {
  [Symbol.iterator]: () => IterableIterator<ArrayItems<T>>;
};

And the Infer result could then be:

type ActionWildcard = FixedLengthArray<['*']>

That would be much more restrictive and true to the intent of the use of size.

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

No branches or pull requests

1 participant