首页
/ TypeBox项目中处理TypeScript枚举与OpenAPI兼容性的实践

TypeBox项目中处理TypeScript枚举与OpenAPI兼容性的实践

2025-06-07 05:47:47作者:郜逊炳

在TypeBox项目中,开发者经常需要处理TypeScript枚举类型与OpenAPI规范的兼容性问题。本文将深入探讨如何安全地使用TypeBox的Type.Unsafe方法来描述枚举字符串,同时保持类型系统的完整性。

问题背景

TypeScript枚举是一种强大的类型系统特性,但在与OpenAPI规范交互时存在兼容性挑战。标准的TypeBoxType.Enum在某些场景下无法满足OpenAPI的要求,这时开发者需要采用Type.Unsafe方法来绕过类型检查。

解决方案实现

我们实现了一个StringEnum工具函数,它能够:

  1. 接受一个TypeScript枚举作为输入
  2. 提取枚举的所有有效值
  3. 自动检测值类型(字符串或数字)
  4. 生成符合OpenAPI规范的枚举定义
function StringEnum<T extends Record<string, string | number>>(item: T): TUnsafe<T[keyof T]> {
  const AllStrings = (values: (string | number)[]) => values.every(value => ValueGuard.IsString(value))
  const AllNumbers = (values: (string | number)[]) => values.every(value => ValueGuard.IsNumber(value))
  
  if (ValueGuard.IsUndefined(item)) throw new Error('Enum undefined or empty')
  
  const values = globalThis.Object.getOwnPropertyNames(item)
    .filter((key) => isNaN(key as never))
    .map((key) => item[key])
  
  const type = (
    AllStrings(values) ? { type: 'string' } :
    AllNumbers(values) ? { type: 'number' } :
    { }
  )
  
  return Type.Unsafe({ ...type, enum: [...new Set(values)] })
}

关键实现细节

  1. 类型安全处理:通过泛型T extends Record<string, string | number>确保输入是枚举类型
  2. 值提取逻辑:使用Object.getOwnPropertyNames配合isNaN过滤掉反向映射
  3. 类型检测:自动识别枚举值是字符串还是数字类型
  4. 去重处理:使用Set确保枚举值唯一性

使用示例

enum MyEnum {
  AAA = 'A',
  BBB = 'B',
}

const Schema = Type.Object({
  value: StringEnum(MyEnum)
})

type SchemaType = Static<typeof Schema> // 推断为 { value: MyEnum }

技术要点

  1. 类型推断:通过T[keyof T]保持完整的类型推断能力
  2. OpenAPI兼容:生成的模式完全符合OpenAPI规范
  3. 错误处理:对空枚举进行了防御性检查
  4. 灵活性:同时支持字符串和数字枚举

总结

这种实现方式完美解决了TypeScript枚举与OpenAPI规范之间的兼容性问题,同时保持了TypeBox强大的类型推断能力。开发者可以安全地在API契约中使用枚举类型,而不用担心与OpenAPI工具的兼容性问题。

登录后查看全文
热门项目推荐
相关项目推荐