如何将TypeScript接口转换为Go结构体?遇动态键难题求助
TypeScript对象建模工具迁移至Go的实现方案
原TypeScript实现
interface SchemaType { [key: string]: { type: string; required?: boolean; default?: any; validate?: any[]; maxlength?: any[]; minlength?: any[], transform?: Function; }; }; class Schema { private readonly schema; constructor(schema: SchemaType) { this.schema = schema; }; public validate(data: object): Promise<object> { // Do something with data return data; }; };
使用方式
const itemSchema = new Schema({ id: { type: String, required: true }, createdBy: { type: String, required: true } });
Go语言初步实现(存在问题)
type SchemaType struct { Key string // I'm not sure about this bit Type string Required bool Default func() Validate [2]interface{} Maxlength [2]interface{} Minlength [2]interface{} Transform func() } type Schema struct { schema SchemaType } func (s *Schema) NewSchema(schema SchemaType) { s.schema = schema } func (s *Schema) Validate(collection string, data map[string]interface{}) map[string]interface{} { // do something with data return data }
遇到的瓶颈
无法在Go中实现TypeScript SchemaType接口里的动态key特性(即字符串键到字段规则的映射结构)。
正确的Go实现方案
在Go里,对应TS中{[key: string]: FieldRule}的结构是map[string]FieldRule,先定义单个字段的规则结构体,再用map承载动态键的映射:
// FieldRule 对应TS中每个字段的配置 type FieldRule struct { Type string Required bool Default interface{} // 可根据需求细化类型,比如func()interface{} Validate []interface{} Maxlength []interface{} Minlength []interface{} Transform func(interface{}) interface{} // 明确输入输出类型,符合Go类型安全 } // Schema 核心结构体,存储字段规则的映射 type Schema struct { schema map[string]FieldRule } // NewSchema 构造函数,初始化Schema实例 func NewSchema(rules map[string]FieldRule) *Schema { return &Schema{ schema: rules, } } // Validate 实现数据校验逻辑 func (s *Schema) Validate(data map[string]interface{}) (map[string]interface{}, error) { // 编写具体校验逻辑:遍历schema规则,检查data中对应字段的合法性 // 示例:返回处理后的数据和可能的错误 return data, nil }
使用示例
func main() { itemSchema := NewSchema(map[string]FieldRule{ "id": { Type: "string", Required: true, }, "createdBy": { Type: "string", Required: true, }, }) // 待校验数据 data := map[string]interface{}{ "id": "123", "createdBy": "user1", } result, err := itemSchema.Validate(data) if err != nil { // 处理校验错误 return } // 处理校验后的结果 }
关键说明
map[string]FieldRule完全匹配TS的动态key结构,每个键对应一个字段的校验规则- 调整
Default和Transform的类型,避免空接口过度使用,同时保留业务灵活性 - 用
NewSchema函数作为构造函数,符合Go的惯用初始化方式 - Validate方法添加
error返回值,增强错误处理能力,符合Go的错误处理规范
内容的提问来源于stack exchange,提问作者whit3.oc7opus
相关产品推荐
相关产品推荐

