diff --git a/tygo/config.go b/tygo/config.go index 0425fbe..34d308b 100644 --- a/tygo/config.go +++ b/tygo/config.go @@ -50,6 +50,12 @@ type PackageConfig struct { // In "types" mode, only type comments are preserved. // If "none" is supplied, no comments are preserved. PreserveComments string `yaml:"preserve_comments"` + + // Set the optional type (null or undefined). + // Supported values: "default", "undefined" (same as "default"), "" (same as "default"), "null". + // Default is "undefined". + // Useful for usage with JSON marshalers that output null for optional fields (e.g. gofiber JSON). + OptionalType string `yaml:"optional_type"` } type Config struct { @@ -82,6 +88,12 @@ func (c Config) PackageConfig(packagePath string) *PackageConfig { if err != nil { log.Fatalf("Invalid config for package %s: %s", packagePath, err) } + + pc.OptionalType, err = normalizeOptionalType(pc.OptionalType) + if err != nil { + log.Fatalf("Invalid config for package %s: %s", packagePath, err) + } + return pc } } @@ -113,6 +125,17 @@ func normalizePreserveComments(preserveComments string) (string, error) { } } +func normalizeOptionalType(optional string) (string, error) { + switch optional { + case "", "default", "undefined": + return "undefined", nil + case "null": + return "null", nil + default: + return "", fmt.Errorf("unsupported optional: %s", optional) + } +} + func (c PackageConfig) IsFileIgnored(pathToFile string) bool { basename := filepath.Base(pathToFile) for _, ef := range c.ExcludeFiles { diff --git a/tygo/write.go b/tygo/write.go index 0db9e00..6dc6a42 100644 --- a/tygo/write.go +++ b/tygo/write.go @@ -373,7 +373,7 @@ func (g *PackageGenerator) writeStructFields(s *strings.Builder, fields []*ast.F f.Type = t.X } - if optional { + if optional && g.conf.OptionalType == "undefined" { s.WriteByte('?') } @@ -381,6 +381,9 @@ func (g *PackageGenerator) writeStructFields(s *strings.Builder, fields []*ast.F if tstype == "" { g.writeType(s, f.Type, nil, depth, false) + if optional && g.conf.OptionalType == "null" { + s.WriteString(" | null") + } } else { s.WriteString(tstype) }