Generate TypeScript interfaces from Go structs/interfaces - useful for JSON RPC

bel

Generate TypeScript interfaces from Go structs/interfaces - useful for JSON RPC

Go Report Card GoDoc gocover.run Stability: Active

Open in Gitpod

bel is used in production in https://gitpod.io.

Getting started

bel is easy to use. There are two steps involved: extract the Typescript information, and generate the Typescript code.

package main

import (
    "github.com/32leaves/bel"
)

type Demo struct {
    Foo string `json:"foo,omitempty"`
    Bar uint32
    Baz struct {
        FirstField  bool
        SecondField *string
    }
}

func main() {
    ts, err := bel.Extract(Demo{})
    if err != nil {
        panic(err)
    }

    err = bel.Render(ts)
    if err != nil {
        panic(err)
    }
}

produces something akin to (sans formatting):

export interface Demo {
    foo?: string
    Bar: number
    Baz: {
        FirstField: boolean
        SecondField: string
    }
}

Converting interfaces

You can also convert Golang interfaces to TypeScript interfaces. This is particularly handy for JSON RPC:

package main

import (
    "os"
    "github.com/32leaves/bel"
)

type DemoService interface {
    SayHello(name, msg string) (string, error)
}

func main() {
    ts, err := bel.Extract((*DemoService)(nil))
    if err != nil {
        panic(err)
    }

    err = bel.Render(ts)
    if err != nil {
        panic(err)
    }
}

produces something akin to (sans formatting):

export interface DemoService {
    SayHello(arg0: string, arg1: string): string
}

Advanced Usage

You can try all the examples mentioned below in Gitpod.

FollowStructs

Follow structs enable the transitive generation of types. See examples/embed-structs.go.

would produce code for the interface UserService, as well as the struct it refers to AddUserRequest, and User because it's referenced by AddUserRequest. Without FollowStructs we'd simply refer to the types by name, but would not generate code for them.

SortAlphabetically

SortAlphabetically sorts all types and their members by alphabetical order. This produces more deterministic/stable output, which is great for making things comparable across pull requests. See examples/sort-alphabetically.go.

EmbedStructs

Embed structs is similar to FollowStructs except that it produces a single canonical type for each structure. Whenever one struct references another, that reference is resolved and the definition of the other is embedded. See examples/embed-structs.go.

NameAnonStructs

NameAnonStructs is kind of the opposite of EmbedStructs. When we encounter a nested anonymous struct, we make give this previously anonymous structure a name and refer to it using this name. See examples/name-anon-structs.go.

CustomNamer

CustomNamer enables full control over the TypeScript type names. This is handy to enforce a custom coding guideline, or to add a prefix/suffix to the generated type names. See examples/custom-namer.go.

Enums

See examples/enums.go.

Go famously does not have enums, but rather type aliases and consts. Using reflection alone there is no way to obtain a comprehensive list of type values, as the linker might optimize and remove some. bel supports the extraction of enums by parsing the Go source code. Note that this is merely a heuristic and may fail in your case. If it does not work, bel falls back to the underlying type.

Enums can be generated as TypeScript enum or as sum types. Use the bel.GenerateEnumsAsSumTypes flag to change this behaviour.

Code Generation

See examples/code-generation.go.

When generating the TypeScript code you might want to wrap everything in a namespace. To that end bel.GenerateNamespace("myNamespaceName") can be used.

By default bel adds a comment to the files it generates. You can influcence this comment (and any other code that comes before the generated code) using bel.GeneratePreamble and bel.GenerateAdditionalPreamble.

You can configure the io.Writer that bel uses using bel.GenerateOutputTo.

Contributing

All contributions/PR/issue/beer are welcome ❤️ .

It's easiest to work with bel using Gitpod: Open in Gitpod

Owner
Christian Weichel
Working on @gitpod-io and werft
Christian Weichel
Similar Resources

[TOOL, CLI] - Filter and examine Go type structures, interfaces and their transitive dependencies and relationships. Export structural types as TypeScript value object or bare type representations.

typex Examine Go types and their transitive dependencies. Export results as TypeScript value objects (or types) declaration. Installation go get -u gi

Dec 6, 2022

K8s-go-structs - All k8s API Go structs

k8s-api go types Why? Its nice to have it all in a single package. . |-- pkg |

Jul 17, 2022

Examples of accepting interfaces and returning structs

Go Interfaces When I started writing tests in Go, I sometimes used interfaces to mock things in tests. Then I discovered that this is not the correct

Dec 27, 2022

Generate Typescript types from Golang source code

🎑 tygo Tygo is a tool for generating Typescript typings from Golang source files that just works. Other than reflection-based methods it preserves co

Dec 16, 2022

convert JSON of a specific format to a type structure(Typescript type or more)

json2type convert JSON of a specific format to a type structure(Typescript type or more) Quick Start CLI Install use go tool install go install github

Mar 28, 2022

Cap'n Proto library and parser for go. This is go-capnproto-1.0, and does not have rpc. See https://github.com/zombiezen/go-capnproto2 for 2.0 which has rpc and capabilities.

Version 1.0 vs 2.0 Update 2015 Sept 20: Big news! Version 2.0 of the go-bindings, authored by Ross Light, is now released and newly available! It feat

Nov 29, 2022

RPC explained by writing simple RPC framework in 300 lines of pure Golang.

Simple GoRPC Learning RPC basic building blocks by building a simple RPC framework in Golang from scratch. RPC In Simple Term Service A wants to call

Dec 17, 2022

Antenna RPC is an RPC protocol for distributed computing, it's based on QUIC and Colfer. its currently an WIP.

aRPC - Antenna Remote Procedure Call Antenna remote procedure call (aRPC) is an RPC protocol focused on distributed processing and HPC. aRPC is implem

Jun 16, 2021

Go Substrate RPC Client (GSRPC)Go Substrate RPC Client (GSRPC)

Go Substrate RPC Client (GSRPC) Substrate RPC client in Go. It provides APIs and types around Polkadot and any Substrate-based chain RPC calls. This c

Nov 11, 2021

Golang-Devnet-Interfaces - Quick example of using Scrapligo and TextFSM to parse interfaces from Devnet Sandbox

Scrapligo & TextFSM This is a simple example of using the Scrapligo library deve

Mar 7, 2022

Generate Terraform schema from Go structs

terraform-schema-gen This repository contains a CLI to generate Terraform schema out of Go structs. The generator relies on kube-openapi as an interme

Sep 13, 2022

Fast JSON parser and validator for Go. No custom structs, no code generation, no reflection

fastjson - fast JSON parser and validator for Go Features Fast. As usual, up to 15x faster than the standard encoding/json. See benchmarks. Parses arb

Jan 5, 2023

RTS: request to struct. Generates Go structs from JSON server responses.

RTS: Request to Struct Generate Go structs definitions from JSON server responses. RTS defines type names using the specified lines in the route file

Dec 7, 2022

Easy JSON parser for Go. No custom structs, no code generation, no reflection

Easy JSON parser for Go. No custom structs, no code generation, no reflection

Dec 28, 2022

An excellent tool for converting json files to structs or classes in any programming language.

An excellent tool for converting json files to structs or classes in any programming language.

Explore Usage » Report Bug · Request Feature Table of Contents About The Project Supported Languages Getting Started Usage Parameters Set Up Your Own

Dec 10, 2022

Go-video-preview-ffmpeg-wrapper - A simple helper wrapper to generate small webm video previews using ffmpeg, useful for web previews.

Go-video-preview-ffmpeg-wrapper A simple helper wrapper to generate small webm video previews using ffmpeg, useful for web previews. Getting Started u

Jan 5, 2022

converts text-formats from one to another, it is very useful if you want to re-format a json file to yaml, toml to yaml, csv to yaml, ... etc

re-txt reformates a text file from a structure to another, i.e: convert from json to yaml, toml to json, ... etc Supported Source Formats json yaml hc

Sep 23, 2022

A smol DNS server (100 loc) that's configured with a static JSON file. Useful for split-dns.

A smol DNS server (100 loc) that's configured with a static JSON file. Useful for split-dns.

Jul 27, 2022

A Golang protobuf plugin used to generate the necessary interfaces to interact with the database

protoc-gen-go-db-enum This protobuf compiler plugin generates the Valuer and Scanner interfaces for enums defined in the proto files. It is highly bas

Sep 9, 2022
Comments
  • Properly extract enums/const

    Properly extract enums/const

    Something like

    type Foo string
    const (
        Bar = "bar"
        Baz = "baz"
    )
    
    type UsesFoo struct {
        Field Foo
    }
    

    results in Field being extracted as type string rather than Foo. Ideally we'd have an enum Foo coming out of the extractor.

    Using Go reflection this cannot be done [1, 2]. We could however parse the Golang source and extract the const values that way.

    [1] https://stackoverflow.com/questions/33189060/is-there-a-way-to-iterate-over-constant-used-as-enum [2] https://groups.google.com/forum/#!topic/golang-nuts/M0ORoEU115o

  • Allow renaming of primitive types

    Allow renaming of primitive types

    Allows renaming primitive types. This is helpful if those types are marshalled in a non standard way.

    In our case, we had a type Timestamp int64 that we are marshalling as a string. With this change, it’s possible to customise the generated typescript type for non struct types as well.

  • Missing error check in fielpath.WalkFunc

    Missing error check in fielpath.WalkFunc

    Stacktrace:

    panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x5584e9]
    
    goroutine 1 [running]:
    github.com/32leaves/bel.NewParsedSourceEnumHandler.func1(0x615603, 0x15, 0x0, 0x0, 0x653880, 0xc000100b10, 0x40, 0x5f6a00)
    	/workspace/go/pkg/mod/github.com/32leaves/[email protected]/enum.go:32 +0x49
    path/filepath.Walk(0x615603, 0x15, 0xc0001318e0, 0x0, 0x1000000006595a0)
    	/home/gitpod/go/src/path/filepath/path.go:404 +0x6a
    github.com/32leaves/bel.NewParsedSourceEnumHandler(0x615603, 0x15, 0x0, 0x0, 0x653880)
    	/workspace/go/pkg/mod/github.com/32leaves/[email protected]/enum.go:31 +0xf7
    main.main()
    	/tmp/build/gitpod-core-components-licensor-typescript--lib.b4eb6140f12b76cf914379726822bcd956b92256/ee/genapi.go:25 +0x8f
    exit status 2
    
Related tags
idiomatic codec and rpc lib for msgpack, cbor, json, etc. msgpack.org[Go]

go-codec This repository contains the go-codec library, the codecgen tool and benchmarks for comparing against other libraries. This is a High Perform

Dec 19, 2022
Some Golang types based on builtin. Implements interfaces Value / Scan and MarshalJSON / UnmarshalJSON for simple working with database NULL-values and Base64 encoding / decoding.

gotypes Some simple types based on builtin Golang types that implement interfaces for working with DB (Scan / Value) and JSON (Marshal / Unmarshal). N

Feb 12, 2022
auto-generate capnproto schema from your golang source files. Depends on go-capnproto-1.0 at https://github.com/glycerine/go-capnproto

bambam: auto-generate capnproto schema from your golang source files. Adding capnproto serialization to an existing Go project used to mean writing a

Sep 27, 2022
Easily and dynamically generate maps from Go static structures

structomap This package helps you to transform your struct into map easily. It provides a structomap.Serializer interface implemented by the structoma

Dec 9, 2022
A high-performance 100% compatible drop-in replacement of "encoding/json"
A high-performance 100% compatible drop-in replacement of

A high-performance 100% compatible drop-in replacement of "encoding/json" You can also use thrift like JSON using thrift-iterator Benchmark Source cod

Jan 7, 2023
Go package for dealing with maps, slices, JSON and other data.

Objx Objx - Go package for dealing with maps, slices, JSON and other data. Get started: Install Objx with one line of code, or update it with another

Dec 27, 2022
protoc-gen-grpc-gateway-ts is a Typescript client generator for the grpc-gateway project. It generates idiomatic Typescript clients that connect the web frontend and golang backend fronted by grpc-gateway.

protoc-gen-grpc-gateway-ts protoc-gen-grpc-gateway-ts is a Typescript client generator for the grpc-gateway project. It generates idiomatic Typescript

Dec 19, 2022
RPC Framework abstraction layer. Provides foundation of the RonyDesc to generate RPC server/client codes.

RonyKit RonyKit provides the abstraction layer for creating a cluster aware API server. By defining separate components for each task, you are almost

Dec 15, 2022
rpc/v2 support for JSON-RPC 2.0 Specification.

rpc rpc/v2 support for JSON-RPC 2.0 Specification. gorilla/rpc is a foundation for RPC over HTTP services, providing access to the exported methods of

Jul 4, 2021
Go library to interface with Solana JSON RPC and WebSocket interfaces
Go library to interface with Solana JSON RPC and WebSocket interfaces

Solana SDK library for Go Go library to interface with Solana JSON RPC and WebSocket interfaces. Clients for Solana native programs, Solana Program Li

Mar 2, 2022