-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexample_test.go
102 lines (76 loc) · 2.04 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package tsreflect_test
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/olahol/tsreflect"
)
type MyStruct struct {
Number int
String int `json:",string"`
Alias string `json:"alias"`
Hidden string `json:"-"`
}
func Example_simple() {
g := tsreflect.New()
var x MyStruct
typ := reflect.TypeOf(x)
g.Add(typ)
value, _ := json.Marshal(x)
fmt.Println(g.DeclarationsTypeScript())
fmt.Printf("const x: %s = %s", g.TypeOf(typ), value)
// Output:
// interface MyStruct { "Number": number; "String": string; "alias": string; }
// const x: MyStruct = {"Number":0,"String":"0","alias":""}
}
type MyCustomStruct struct {
A string
B string
C string
}
func (s MyCustomStruct) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", strings.Join([]string{s.A, s.B, s.C}, ","))), nil
}
// TypeScriptType(g *Generator, optional bool) string
func (s MyCustomStruct) TypeScriptType(*tsreflect.Generator, bool) string {
return "string"
}
func Example_customTypeScriptType() {
g := tsreflect.New()
x := MyCustomStruct{
A: "1",
B: "2",
C: "3",
}
typ := reflect.TypeOf(x)
g.Add(typ)
value, _ := json.Marshal(x)
fmt.Println(g.DeclarationsTypeScript())
fmt.Printf("const x: %s = %s", g.TypeOf(typ), value)
// Output:
// const x: string = "1,2,3"
}
func ExampleWithFlatten() {
g := tsreflect.New(tsreflect.WithFlatten())
var x MyStruct
typ := reflect.TypeOf(x)
g.Add(typ)
value, _ := json.Marshal(x)
fmt.Println(g.DeclarationsTypeScript())
fmt.Printf("const x: %s = %s", g.TypeOf(typ), value)
// Output:
// const x: { "Number": number; "String": string; "alias": string; } = {"Number":0,"String":"0","alias":""}
}
func ExampleWithNamer() {
g := tsreflect.New(tsreflect.WithNamer(tsreflect.PackageNamer))
var x json.SyntaxError
typ := reflect.TypeOf(x)
g.Add(typ)
value, _ := json.Marshal(x)
fmt.Println(g.DeclarationsTypeScript())
fmt.Printf("const x: %s = %s", g.TypeOf(typ), value)
// Output:
// interface EncodingJsonSyntaxError { "Offset": number; }
// const x: EncodingJsonSyntaxError = {"Offset":0}
}