[英]How to convert TypeScript interface to Go struct?
I'm trying to convert my object modeling tool, built with TypeScript, to Go.我正在尝试将使用 TypeScript 构建的 object 建模工具转换为 Go。
What I have in TypeScript is:我在 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;
};
};
So that I can then do:这样我就可以做:
const itemSchema = new Schema({
id: {
type: String,
required: true
},
createdBy: {
type: String,
required: true
}
});
I've only gotten this far with Go:我只用 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
}
I'm a little stuck mainly because of the dynamic "key" in the SchemaType interface and am not sure how to replicate this in Go...我有点卡住了,主要是因为 SchemaType 接口中的动态“键”,我不确定如何在 Go 中复制它......
The [key string]:
part means that it's a dictionary with keys of type string
. [key string]:
部分表示它是一个包含string
类型键的字典。 In Go that would be a map[string]<some type>
.在 Go 中,这将是一个
map[string]<some type>
。
type SchemaType map[string]SchemaTypeEntry
type SchemaTypeEntry struct {
Type string
Required bool
// ...
}
or, drop the SchemaType
type and change Schema
:或者,删除
SchemaType
类型并更改Schema
:
type Schema struct {
schema map[string]SchemaTypeEntry
}
Now, about the other fields, the look odd as you have defined them, and it's likely that it will not work the way you are showing here.现在,关于其他字段,您定义它们时看起来很奇怪,而且它很可能不会像您在此处显示的那样工作。
Default
would be a value, not a func()
(a function that doesn't return anything). Default
将是一个值,而不是func()
(不返回任何内容的 function)。 You don't know what type the value is, so the type should be interface {}
or any
(since Go 1.18 - an alias for interface {}
).您不知道该值是什么类型,因此类型应该是
interface {}
或any
(自 Go 1.18 - interface {}
的别名)。
Transform
- that would likely be a function that takes a value, transforms it, and returns a value - func(interface{}) interface{}
Transform
- 这可能是一个 function,它接受一个值,转换它并返回一个值 - func(interface{}) interface{}
No idea what MinLength
, MaxLength
and Validate
stand for in this context - it is unclear why they are arrays in Javascript, and how you can be sure that they are of exactly length 2 in Go.不知道
MinLength
、 MaxLength
和Validate
在这种情况下代表什么——不清楚为什么它们在 Javascript 中是 arrays,以及如何确定它们在 Go 中的长度正好是 2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.