You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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
    }
    // 处理校验后的结果
}

关键说明

  1. map[string]FieldRule完全匹配TS的动态key结构,每个键对应一个字段的校验规则
  2. 调整Default和Transform的类型,避免空接口过度使用,同时保留业务灵活性
  3. 用NewSchema函数作为构造函数,符合Go的惯用初始化方式
  4. Validate方法添加error返回值,增强错误处理能力,符合Go的错误处理规范

内容的提问来源于stack exchange,提问作者whit3.oc7opus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:50:23