Skip to content

Wrong TypeScript type when using encore:"optional" without omitempty  #1623

@melkstam

Description

@melkstam

When using the encore:"optional" and generating a client, the field is marked as field?: type. However, this typing is only correct when omitempty is included in the json tag.

Sometimes you actually don't want to add an omitempty, for example if you want to convey that there is a field here, but it just has no value.


For example, take this simple endpoint:

package hello

import (
	"context"
)

type HelloResponse struct {
	Foo *string `json:"foo" encore:"optional"`
	Bar *string `json:"bar,omitempty" encore:"optional"`
}

// encore:api public
func Hello(ctx context.Context) (*HelloResponse, error) {
	return &HelloResponse{
		Foo: nil,
		Bar: nil,
	}, nil
}

When generating a TypeScript client, the type of HelloResponse is

export interface HelloResponse {
    foo?: string
    bar?: string
}

However, when actually calling the endpoint and parsing it in JavaScript, the response you get is

{
    "foo": null
}

which actually matches to the type

export interface HelloResponse {
    foo: string | null
    bar?: string
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions