Translating Golang functions to TypeScript
jarble opened this issue · 3 comments
Could this compiler be extended to translate Golang functions as well as Golang structs to TypeScript?
For example, this Go function could be easily translated to TypeScript:
func add(x f64, y f64) int {
return x + y
}
This would be the equivalent function in TypeScript:
export function add(x:number,y:number):number{
return x+y;
}
It is possible to translate a subset of Go to TypeScript in this way, and there are several other features of Go that could be easily translated:
forloops would becomewhileloops,- slices would become arrays in TypeScript,
- Generics in Go would become generics in TypeScript
- and many others: anonymous functions, switch statements, type conversions, etc.
I don't think you could easily extend this to a state where it would be broadly useful. Most code depends upon other libraries, including the standard library. If you include, those things, then a feature needs to know how to translate those or somehow replace them with Typescript equivalents with often varying syntax or quirks that don't match Go. This isn't to say you can't do this, but it's far larger in scope than this project and should not be here. Luckily, nearly what you want also already exists in the form of gopherjs. I recommend you take a look at that project for transpiling Go to Javascript.
I would like to have functions as well, but in completely different way.
For example in go:
type MyService struct {
}
func (srv *MyService) Add(model MyModel) string {
id := db.Add(model);
return id
}
func (srv *MyService) Get(id string) MyModel {
model := db.Get(id);
return model
}Results to:
export class MyService {
axios: any; // or any other http or rpc client
Add(model: MyModel): Promise<string> {
return axios.post("MyService/Add", { body: { model } });
}
Get(id: string): Promise<MyModel> {
return axios.post("MyService/Get", { body: { model } });
}
}I have Wails app and I would like to generate services to call backend using one single route in which case instead of axios it would be some function to call the backend.
@fairking What you're suggesting is a solution for a completely different problem than the one this library solves. Also, it's highly dependant on the http library/framework you use.
But, generally, transpiling code is something I don't plan to implement because it is way too complicated and I don't have the time to mantain that.