chore: bump version to 0.0.43, enhance JSON Schema type inference, and add usage examples
This commit is contained in:
@@ -13,22 +13,34 @@ type Pos = {
|
||||
|
||||
// JSON Schema 类型推断 - 使用更精确的类型匹配
|
||||
type InferFromJSONSchema<T> =
|
||||
// 处理带 enum 的字符串类型
|
||||
T extends { type: "string"; enum: readonly (infer E)[] } ? E :
|
||||
T extends { type: "string"; enum: (infer E)[] } ? E :
|
||||
// 基础类型
|
||||
T extends { type: "string" } ? string :
|
||||
T extends { type: "number" } ? number :
|
||||
T extends { type: "integer" } ? number :
|
||||
T extends { type: "boolean" } ? boolean :
|
||||
// 对象类型 - 检查是否有 properties
|
||||
T extends { type: "object"; properties: infer P }
|
||||
? { [K in keyof P]: InferFromJSONSchema<P[K]> }
|
||||
: T extends { type: "array"; items: infer I }
|
||||
? {
|
||||
[K in keyof P]: InferFromJSONSchema<P[K]>
|
||||
}
|
||||
: // 数组类型
|
||||
T extends { type: "array"; items: infer I }
|
||||
? Array<InferFromJSONSchema<I>>
|
||||
: // 默认情况 - 如果是对象但没有 type 字段,尝试递归推断
|
||||
T extends Record<string, any>
|
||||
? T extends { properties: infer P }
|
||||
? { [K in keyof P]: InferFromJSONSchema<P[K]> }
|
||||
: unknown
|
||||
: unknown;
|
||||
|
||||
// 统一类型推断:支持 Zod schema 和原始 JSON Schema
|
||||
type InferType<T> =
|
||||
T extends z.ZodType<infer U> ? U : // Zod schema
|
||||
T extends { type: infer TType } ? InferFromJSONSchema<T> : // 任何包含 type 字段的 JSON Schema(忽略 $schema)
|
||||
T extends { properties: infer P } ? InferFromJSONSchema<T> : // 处理没有 type 但有 properties 的对象
|
||||
T;
|
||||
|
||||
// 提取 args 对象,将每个 Zod schema 或 JSON Schema 转换为实际类型
|
||||
|
||||
Reference in New Issue
Block a user