With the follow example, can I introduce a type from ParsedType based on InterceptInit.schema type that is a ZodSchema using z.infer<typeof schema>?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
30 messages · Page 1 of 1 (latest)
With the follow example, can I introduce a type from ParsedType based on InterceptInit.schema type that is a ZodSchema using z.infer<typeof schema>?
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@vivid flame Here's a shortened URL of your playground link! You can remove the full link from your message.
the link is invalid
Sorry about it, updated! Thanks
!ts
import { ZodError, ZodSchema, z } from 'zod'
// ^^^^^
// Cannot find module 'zod' or its corresponding type declarations.
interface HandlerParams<Type> {
parsed?: Type
}
interface InteceptInit<Schema extends ZodSchema> {
handler: (params: HandlerParams<z.TypeOf<Schema>>) => Promise<any>
schema?: Schema
secure?: boolean
}
export function intercept<Schema extends ZodSchema>(init: InteceptInit<Schema>) {
return async function (input: unknown): Promise<unknown> {
try {
let parsed
if (init.schema) {
parsed = await init.schema.parseAsync({
input
})
}
return await init.handler({ parsed })
} catch (error) {
throw error
}
}
}
The code actually works but parsed still being a "any" type
a ZodSchema
I trying to get parsed of type of z.infer<typeof mySchemaParameter>
I using to call intercept like this:
export const POST = intercept({
handler: async ({ parsed }) => {
console.log(parse.body.name) // but no completion for parse properties
},
schema: z.object({
body: z.object({
name: z.string().min(2),
code: z.string().max(6),
email: z.string().email(),
phone: z.string(),
token: z.string(),
}),
}),
})
hm
oh yknow what
oh
@vivid flame hover over intercept, what is Schema being inferred as?
@balmy root
!ts
import { ZodError, ZodSchema, z } from 'zod'
// ^^^^^
// Cannot find module 'zod' or its corresponding type declarations.
type NoInfer<T> = [T][T extends T ? 0 : never]
interface HandlerParams<Type> {
parsed?: Type
}
interface InteceptInit<Schema extends ZodSchema> {
handler: (params: HandlerParams<z.TypeOf<NoInfer<Schema>>>) => Promise<any>
schema?: Schema
secure?: boolean
}
export function intercept<Schema extends ZodSchema>(init: InteceptInit<Schema>) {
return async function (input: unknown): Promise<unknown> {
try {
let parsed
if (init.schema) {
parsed = await init.schema.parseAsync({
input
})
}
return await init.handler({ parsed })
} catch (error) {
throw error
}
}
}
edited version with NoInfer type to try and fix it