繁体   English   中英

如何将 TypeScript 接口转换为 Go 结构?

[英]How to convert TypeScript interface to Go struct?

我正在尝试将使用 TypeScript 构建的 object 建模工具转换为 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
}

我有点卡住了,主要是因为 SchemaType 接口中的动态“键”,我不确定如何在 Go 中复制它......

[key string]:部分表示它是一个包含string类型键的字典。 在 Go 中,这将是一个map[string]<some type>

type SchemaType map[string]SchemaTypeEntry

type SchemaTypeEntry struct {
  Type      string
  Required  bool
  // ...
}

或者,删除SchemaType类型并更改Schema

type Schema struct {
    schema map[string]SchemaTypeEntry
}

现在,关于其他字段,您定义它们时看起来很奇怪,而且它很可能不会像您在此处显示的那样工作。

Default将是一个值,而不是func() (不返回任何内容的 function)。 您不知道该值是什么类型,因此类型应该是interface {}any (自 Go 1.18 - interface {}的别名)。

Transform - 这可能是一个 function,它接受一个值,转换它并返回一个值 - func(interface{}) interface{}

不知道MinLengthMaxLengthValidate在这种情况下代表什么——不清楚为什么它们在 Javascript 中是 arrays,以及如何确定它们在 Go 中的长度正好是 2。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM