• Stars
    star
    138
  • Rank 264,508 (Top 6 %)
  • Language
    Go
  • Created over 6 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate Typescript classes/interfaces out of Go structs

struct2ts GoDoc

An extremely simple and powerful Go struct to Typescript Class generator.

Inspired by tkrajina/typescriptify-golang-structs.

Install

go get -u -v github.com/OneOfOne/struct2ts/...

Features

  • Fairly decent command line interface if you don't wanna write a generator yourself.
  • Automatically handles Go int64 timestamps <-> Javascript Date.
  • Automatically handles json tags.

Options

There's an extra struct tag to control the output, ts, valid options are

  • - omit this field.
  • date handle converting time.Time{}.Unix() <-> javascript Date.
  • ,no-null only valid for struct fields, forces creating a new class rather than using null in TS.
  • ,null allows any field type to be null.

Example

  • Input:
type OtherStruct struct {
	T time.Time `json:"t,omitempty"`
}

type ComplexStruct struct {
	S           string       `json:"s,omitempty"`
	I           int          `json:"i,omitempty"`
	F           float64      `json:"f,omitempty"`
	TS          *int64       `json:"ts,omitempty" ts:"date,null"`
	T           time.Time    `json:"t,omitempty"` // automatically handled
	NullOther   *OtherStruct `json:"o,omitempty"`
	NoNullOther *OtherStruct `json:"nno,omitempty" ts:",no-null"`
}
  • Output:
// ... helpers...
// struct2ts:github.com/OneOfOne/struct2ts_test.ComplexStructOtherStruct
class ComplexStructOtherStruct {
	t: Date;

	constructor(data?: any) {
		const d: any = (data && typeof data === 'object') ? ToObject(data) : {};
		this.t = ('t' in d) ? ParseDate(d.t) : new Date();
	}

	toObject(): any {
		const cfg: any = {};
		cfg.t = 'string';
		return ToObject(this, cfg);
	}
}

// struct2ts:github.com/OneOfOne/struct2ts_test.ComplexStruct
class ComplexStruct {
	s: string;
	i: number;
	f: number;
	ts: Date | null;
	t: Date;
	o: ComplexStructOtherStruct | null;
	nno: ComplexStructOtherStruct;

	constructor(data?: any) {
		const d: any = (data && typeof data === 'object') ? ToObject(data) : {};
		this.s = ('s' in d) ? d.s as string : '';
		this.i = ('i' in d) ? d.i as number : 0;
		this.f = ('f' in d) ? d.f as number : 0;
		this.ts = ('ts' in d) ? ParseDate(d.ts) : null;
		this.t = ('t' in d) ? ParseDate(d.t) : new Date();
		this.o = ('o' in d) ? new ComplexStructOtherStruct(d.o) : null;
		this.nno = new ComplexStructOtherStruct(d.nno);
	}

	toObject(): any {
		const cfg: any = {};
		cfg.i = 'number';
		cfg.f = 'number';
		cfg.t = 'string';
		return ToObject(this, cfg);
	}
}
// ...exports...

Command Line Usage

➤ struct2ts -h
usage: struct2ts [<flags>] [<pkg.struct>...]

Flags:
	-h, --help                  Show context-sensitive help (also try --help-long
								and --help-man).
		--indent="\t"           Output indentation.
	-m, --mark-optional-fields  Add `?` to fields with omitempty.
	-6, --es6                   generate es6 code
	-C, --no-ctor               Don't generate a ctor.
	-T, --no-toObject           Don't generate a Class.toObject() method.
	-E, --no-exports            Don't automatically export the generated types.
	-D, --no-date               Don't automatically handle time.Unix () <-> JS
								Date().
	-H, --no-helpers            Don't output the helpers.
	-N, --no-default-values     Don't assign default/zero values in the ctor.
	-i, --interface             Only generate an interface (disables all the other
								options).
	-s, --src-only              Only output the Go code (helpful if you want to
								edit it yourself).
	-p, --package-name="main"   the package name to use if --src-only is set.
	-k, --keep-temp             Keep the generated Go file, ignored if --src-only
								is set.
	-o, --out="-"               Write the output to a file instead of stdout.
	-V, --version               Show application version.

Args:
	[<pkg.struct>]  List of structs to convert (github.com/you/auth/users.User,
					users.User or users.User:AliasUser).

Advanced

Custom output per model

type CustomTypescript interface {
	RenderCustomTypescript(w io.Writer) (err error)
}

If your model implements a RenderCustomTypescript(w io.Writer) (err error) function it will inject what ever you write to the writer at the end of the model. struct2ts will handle the first level of indenting for you.

TODO

  • Use xast to skip reflection.
  • Support annoymous structs.
  • Support ES6.

License

This project is released under the BSD 3-clause "New" or "Revised" License.

More Repositories

1

xxhash

A native implementation of the excellent XXHash hashing algorithm.
Go
411
star
2

lfchan

A scalable lock-free channel.
Go
133
star
3

netchan

Go channels over a network.
Go
83
star
4

go-utils

Random Go Language utilities that don't warrant their own repos.
Go
50
star
5

cmap

A sharded map implementation to support fast concurrent access and swap/update operations.
Go
46
star
6

genx

GenX: Generics For Go, Yet Again.
Go
37
star
7

go-nfqueue

Go Wrapper For Creating IPTables NFQueue clients in Go
Go
29
star
8

xast

xast: ast rewriter with built-in clean up.
Go
26
star
9

pia-socks-proxy

An Alpine Linux container running a socks5 proxy (using dante) via Private Internet Access (OpenVPN).
Dockerfile
16
star
10

git-go-vendor

Simple go vendoring using git submodules.
Go
12
star
11

cch

cch: closable safe go channels
Go
7
star
12

radix

radix: a go radix tree with nearest matching
Go
6
star
13

generics.pw

source code for https://generics.pw
Go
4
star
14

genh

genh: generics helpers
Go
4
star
15

dynamic-routes

Dynamic routes for Express.JS
JavaScript
4
star
16

cgoVSsyso

Go
3
star
17

seahash

A SeaHash Implentation in Go
Go
2
star
18

bctx

context helpers
Go
2
star
19

vscode-save-runner

Save Runner for Visual Studio Code
TypeScript
2
star
20

wjsu

syscall/js wasm helper
Go
2
star
21

dvcs-helper

A helper to (dumb)-sync DVCS repos over php/ftp.
Python
2
star
22

Secure-Browser-Chat

1
star
23

closer

Go
1
star
24

otk

Go
1
star
25

stc

Go
1
star
26

rlog

Go
1
star
27

slowbolt

slowbolt: log slow update/view bolt calls
Go
1
star
28

jdb

A file-backed ACID in-memory k/v data store.
Go
1
star
29

limiter

Go
1
star
30

skiplist

a simple skiplist
Go
1
star
31

msgpack

Go
1
star
32

mgo.ejson

A simple package to Marshal/Unmarshal MongoDB's EJson in Go.
Go
1
star
33

webview

Go
1
star
34

oerrs

Yet another go package with an error list
Go
1
star
35

td

TD Ameritrade unofficial Go API Client
Go
1
star
36

segmentedSlice

A fast, index-able, sort-able, grow-only Slice.
Go
1
star
37

etc-fish

My Fish Shell configuration
Shell
1
star