Thursday, February 4, 2016

typescriptify golang structs

I'm a big fan of Go(lang).

I know, I know, Go don't have generics. I miss them, too. But on the other side -- it's simple, it's fast, vim go is great. Writing code is straightforward, it's readable. Golang is more like a better C (with a more consistent API and a garbage collection) with a feeling of a scripting language. It is not a "better Java".

Another language I (started to) like is Typescript. Not because I especially like the language or its syntax. It's because it is:
  • typesafe,
  • compiled to Javascript and the resulting code is similar (almost line-to-line) to the original Typescript code (making debugging very easy).
In my latest side project I decided to go the Go+Typescript way. There was only one thing missing. It is a web application with a lot of Javascript (i.e. Typescript code), but the data used in Typescript was not typesafe. On the server, the data is represented with Golang structs, but Typescript receives only their JSON representation. 

I solved the problem by writing a library which converts Golang structs to Typescript classes: github.com/tkrajina/typescriptify-golang-structs

It's simple, you just:
tscriptify -package=package/with/your/models -target=target_ts_file.ts Model1 Model2
....and then include target_ts_file.ts in your TypeScript scripts.

Make this step part of your bild process and... Now, if you change a field name in Golang -- the javascript/TypeScript compile will fail!

No comments:

Post a Comment