Skip to content

Unable to support converting to optional properties with null union types #94

@dinoc

Description

@dinoc

With this tygo.yaml configuration:

packages:
  - path: "github.com/..."
    optional_type: "null"

If I have this struct:

type Namespaces struct {
	Create *bool   json:"create,omitempty"
	API    *string json:"api,omitempty"
}

I would expect the converted typescript to be:

export interface Namespaces {
  create?: boolean | null;
  api?: string | null;
}

The actual result that I get is:

export interface Namespaces {
  create: boolean | null;
  api: string | null;
}

I'd expect the omitempty tag to make the conversion to be an optional field (?) in typescript.

And with the yaml configuration set to optional_type: "null", I'd expect this to add | null to the converted type which it does correctly. But after playing around with different configurations, I can never get a converted typescript field to be BOTH an optional type (?) and a null union type.

In write.go, starting on line 382, I see this code checking equality with OptionalType. But then a few lines later, it is also checking for equality with OptionalType but for a different value. So it appears it can never be both an optional field with a null union type.

			if optional && g.conf.OptionalType == "undefined" {
				s.WriteByte('?')
			}

			s.WriteString(": ")

			if tstype == "" {
				g.writeType(s, f.Type, nil, depth, false)
				if optional && g.conf.OptionalType == "null" {
					s.WriteString(" | null")
				}
			} else {
				s.WriteString(tstype)
			}
			s.WriteByte(';')

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions