Open pincman opened 1 month ago
@pincman
Can you provide minimal code to reproduce it? It's long and verbose, including unnecessary modules to reproduce.
@pincman
Can you provide minimal code to reproduce it? It's long and verbose, including unnecessary modules to reproduce.
Yes, of course.
export const postSchema = z
.object({
id: z.string(),
// ...
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
})
.strict();
const createGetItemByIdApi = (api: OpenAPIHono) => {
return api.openapi(
createRoute({
// ...
responses: {
200: {
content: {
'application/json': {
schema: postSchema,
},
},
},
},
}),
async (c) => {
try {
const { id } = c.req.param();
const result = await queryPostItemById(id);
return c.json(result) as any;
} catch (error) {
return c.json({ error }, 500);
}
},
);
};
in next.js
export const formatChineseTime = (date: Date) => {
// some code
}
const PostItemPage: FC<{ params: { item: string } }> = async ({ params }) => {
// const post = await queryPostItem(params.item);
const result = await apiClient.api.posts[':item'].$get({ param: { item: params.item } });
return <time className="tw-ellips">
{!isNil(post.updatedAt)
? formatChineseTime(post.updatedAt)
: formatChineseTime(post.createdAt)}
</time>
}
type error "Argument of type 'string' is not assignable to parameter of type 'Date'"
@pincman thank you for giving the code.
Though you might not like it, this is not a bug. This issue is not only @hono/zod-openapi
matter, it's correct hono
behavior. If it returns the values with c.json()
. The value includes the Date
object converted to string
because it uses JSON.stringify()
. So, the value that you get from the client will be string
:
const app = new Hono()
const routes = app.get('/', (c) => {
// d is converted to string with JSON.stringify()
return c.json({
d: new Date()
})
})
const client = hc<typeof routes>('/')
const res = await client.index.$get()
const data = await res.json()
const d = data.d // string
This is not a bug, correct behavior.
I may not have expressed myself clearly. The value of the date type will be a string, this is certainly the case. However, why is the inferred type also a string rather than a date?
I may not have expressed myself clearly. The value of the date type will be a string, this is certainly the case. However, why is the inferred type also a string rather than a date?
Yes. It will be string
. The type definition should follow the actual value.
I'm using hono.js in next.js. When using openapi and zod for data validation, I've found that it's not possible to correctly infer the types of input values or response values through zod. For example:
However, the types inferred by zod itself are fine, such as:
What could be the reason for this?