Repository navigation
Wrapping nested generics in ArkType #1417
|
Hi guys! I'm trying to migrate to ArkType from Zod, but I have these very nice generic function for creating schemas that allow me to dynamically create schemas based on keys of objects. I want to convert these to ArkType but I'm having some trouble converting the generics, since I need to add validations like min length/defaults to the generics and it doesn't seem that simple. Would be great if anyone could help out! Example: export interface SortItem<T extends string> {
key: T;
order: SortOrder;
}
export const createSortItemSchema = <T extends z.ZodType<string>>(sortKeySchema: T) =>
z.object({
key: sortKeySchema,
order: sortOrderSchema,
});export interface BasePaginationParams<TSortKey extends string> {
limit?: number;
sortBy?: SortItem<TSortKey>[];
}
export const createBasePaginationParamsSchema = <TSortKeySchema extends z.ZodType<string>>(
sortKeySchema: TSortKeySchema,
minSortBy = 0,
defaultSortBy: SortItem<TSortKeySchema["_type"]>[] = [],
) =>
z.object({
limit: z.number().int().min(1).max(MAX_READ_LIMIT).default(DEFAULT_READ_LIMIT),
sortBy: z.array(createSortItemSchema(sortKeySchema)).min(minSortBy).default(defaultSortBy),
});export interface CursorPaginationParams<TSortKey extends string> extends BasePaginationParams<TSortKey> {
// This will be a serialised string of all the cursors based on sorting
cursor?: string;
}
export const createCursorPaginationParamsSchema = <TSortKeySchema extends z.ZodType<string>>(
sortKeySchema: TSortKeySchema,
defaultSortBy: SortItem<TSortKeySchema["_type"]>[],
) =>
// We need at least one sort item so we can derive a primary cursor for pagination
createBasePaginationParamsSchema(sortKeySchema, 1, defaultSortBy).merge(
z.object({
cursor: z.string().optional(),
}),
);Then finally example usage where I have full type-safety over the keys, and it knows to autocomplete to choose one of the keys for the argument in the function: const readRoomsInputSchema = createCursorPaginationParamsSchema(selectRoomSchema.keyof(), [
{ key: "updatedAt", order: SortOrder.Desc },
]).default({});
export type ReadRoomsInput = z.infer<typeof readRoomsInputSchema>;I'm not sure how to work with these more complex nested type functions in ArkType, and would be great if someone could help me out here, thanks! PS: Some other questions I have whilst I'm migrating...
selectPostSchema
.pick({ description: true })
.extend({ description: z.string().min(1) })
.merge(z.object({ [selectPostSchema.keyof().Values.parentId]: selectPostSchema.shape.parentId.unwrap() }))or z.object({
[selectPostSchema.keyof().Values.parentId]: selectPostSchema.shape.parentId.default(null),
})
.default({})
type({
limit: `0 < number.integer <= ${MAX_READ_LIMIT} = ${DEFAULT_READ_LIMIT}`,
sortBy: createSortItemSchema(sortKeySchema).array().atLeastLength(minSortBy).default(() => defaultSortBy),
});I've tried super hard here with the default, but for some reason, it doesn't really let me do any defaults at all which is annoying and also defaults don't return just the type for me to infer unlike zod, so I'm also not sure what the best practice is for inferring things with defaults.. The error I get is roughly This is also an issue with compatibility for TRPC, since I want to be able to omit certain parameters and provide defaults for them, so I don't need to pass them when calling TRPC, and zod allows this, but the types returned by arktype when using .default() is completely incompatible |
Replies: 1 comment
|
For the pagination case, one workaround is to keep the schema factory generic but apply the array default after the key type has been instantiated. This avoids forcing TypeScript to resolve ArkType's default-input calculation while This version compiles with ArkType 2.2.9 and TypeScript 5.9.3 in strict mode, without a cast: import { type, type Type } from "arktype"
function pagination<K extends string>(key: Type<K>) {
const sortItems = type({
key,
order: '"asc" | "desc"'
}).array().atLeastLength(1)
return {
sortItems,
base: type({
limit: "1 <= number.integer <= 100 = 20",
"cursor?": "string"
})
}
}
const room = pagination(type('"updatedAt" | "name"'))
const readRoomsInputSchema = room.base.merge({
sortBy: room.sortItems.default(() => [
{ key: "updatedAt", order: "desc" }
])
})
type Input = typeof readRoomsInputSchema.inferIn
type Output = typeof readRoomsInputSchema.infer
const input: Input = {}
readRoomsInputSchema.assert(input)
// { limit: 20, sortBy: [{ key: "updatedAt", order: "desc" }] }The default's Two related details:
I checked the successful defaults and overrides, lower/upper/integer limit failures, invalid keys/orders, empty arrays, invalid cursors, and default-reference isolation at runtime. I also reproduced the generic |
For the pagination case, one workaround is to keep the schema factory generic but apply the array default after the key type has been instantiated. This avoids forcing TypeScript to resolve ArkType's default-input calculation while
Kis still generic.This version compiles with ArkType 2.2.9 and TypeScript 5.9.3 in strict mode, without a cast: