Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ebe30cd

Browse files
committed
feat: support omitzero field tag
1 parent 437443f commit ebe30cd

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

convert.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -679,17 +679,24 @@ func (ts *Typescript) buildStruct(obj types.Object, st *types.Struct) (*bindings
679679
// Use the json name if present
680680
jsonTag, err := tags.Get("json")
681681
if err == nil {
682-
if jsonTag.Name == "-" {
682+
if jsonTag.Name == "-" && len(jsonTag.Options) == 1 {
683683
// Completely ignore this field.
684+
// The tag `"-,"` names the field as "-".
684685
continue
685686
}
686687
// Empty tags are ignored.
687688
if jsonTag.Name != "" {
688689
tsField.Name = jsonTag.Name
689690
}
690-
if len(jsonTag.Options) > 0 && jsonTag.Options[0] == "omitempty" {
691+
if len(jsonTag.Options) > 0 && (jsonTag.Options[0] == "omitempty" || jsonTag.Options[0] == "omitzero") {
691692
tsField.QuestionToken = true
692693
}
694+
695+
if strings.Contains(tsField.Name, "-") {
696+
// Unsure how else to handle this. Name with a hyphen in them
697+
// are not valid field names, so we need to wrap them in quotes.
698+
tsField.Name = fmt.Sprintf("%q", tsField.Name)
699+
}
693700
}
694701

695702
// Infer the type.

testdata/tags/tags.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package tags
2+
3+
type Tags struct {
4+
NoTag int `json:"no_tag"`
5+
OmitEmpty int `json:"omit_empty,omitempty"`
6+
OnlyOmitEmpty int `json:",omitempty"`
7+
Ignore int `json:"-"`
8+
// Hypen appears in JSON as key "-"
9+
// See https://pkg.go.dev/encoding/json@master#Marshal
10+
// https://go.dev/play/p/vsW07aIi_Pj
11+
Hyphen int `json:"-,"`
12+
OmitZero int `json:"omit_zero,omitzero"`
13+
OnlyOmitZero int `json:",omitzero"`
14+
}

testdata/tags/tags.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// Code generated by 'guts'. DO NOT EDIT.
2+
3+
// From tags/tags.go
4+
export interface Tags {
5+
readonly no_tag: number;
6+
readonly omit_empty?: number;
7+
readonly OnlyOmitEmpty?: number;
8+
readonly "-": number;
9+
readonly omit_zero?: number;
10+
readonly OnlyOmitZero?: number;
11+
}

0 commit comments

Comments
 (0)