如何將 TypeScript 介面轉換為 Go 結構體?
php小編新一為您介紹如何將 TypeScript 介面轉換為 Go 結構體。當我們在前端使用 TypeScript 開發時,經常會定義介面來描述資料結構。而在後端使用 Go 語言開發時,需要將這些介面轉換為對應的結構體。本文將從基本型別、巢狀類型、選用型別等方面詳細說明如何進行轉換。透過本文的指導,您將能夠輕鬆地將 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 }
我有點卡住了,主要是因為schematype 介面中的動態“鍵”,並且不知道如何在go 中複製它......
解決方法
#[key string]:
部分意味著它是一個鍵類型為string
的字典。在 go 中,這將是 map[string]<some 類型 >
。
type schematype map[string]schematypeentry type schematypeentry struct { type string required bool // ... }
或者,刪除 schematype
類型並更改 schema
:
type Schema struct { schema map[string]SchemaTypeEntry }
現在,關於其他字段,您定義它們時看起來很奇怪,並且很可能不會按照您在此處顯示的方式工作。
default
將會是一個值,而不是 func()
(不傳回任何內容的函數)。您不知道該值是什麼類型,因此該類型應該是 interface {}
或 any
(自 go 1.18 起 - interface {}
的別名)。
transform
- 這可能是接受值、轉換它並傳回值的函式 - func(interface{}) 介面{}
不知道minlength
、maxlength
和validate
在這種情況下代表什麼- 不清楚為什麼它們在javascript 中是數組,以及如何確定它們在go 中的長度恰好為2。
以上是如何將 TypeScript 介面轉換為 Go 結構體?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)