tkrajina / typescriptify-golang-structs

A Golang struct to TypeScript class/interface converter
Apache License 2.0
505 stars 87 forks source link

Nested Struct Won't Convert #56

Open wolveix opened 2 years ago

wolveix commented 2 years ago

Hey! Firstly, thank you so much for this project, it is incredibly helpful! :)

When a struct has an implicitly declared struct within it, Typescriptify doesn't know how to handle it and ends up returning nothing.

The struct in question:

type DashboardMetrics struct {
    BusinessDailyTotal struct {
        Monday    float64 `json:"monday" yaml:"monday"`
        Tuesday   float64 `json:"tuesday" yaml:"tuesday"`
        Wednesday float64 `json:"wednesday" yaml:"wednesday"`
        Thursday  float64 `json:"thursday" yaml:"thursday"`
        Friday    float64 `json:"friday" yaml:"friday"`
    } `json:"business_daily_total" yaml:"business_daily_total"`
    BusinessWeeklyTotal float64 `json:"business_weekly_total" yaml:"business_weekly_total"`
}

The generated Typescript:

export class DashboardMetrics {
    business_daily_total: ;
    business_weekly_total: number;

    constructor(source: any = {}) {
        if ('string' === typeof source) source = JSON.parse(source);
        this.business_daily_total = this.convertValues(source["business_daily_total"], );
        this.business_weekly_total = source["business_weekly_total"];
    }

    convertValues(a: any, classs: any, asMap: boolean = false): any {
        if (!a) {
            return a;
        }
        if (a instanceof Array) {
            return (a as any[]).map(elem => this.convertValues(elem, classs));
        } else if ("object" === typeof a) {
            if (asMap) {
                for (const key of Object.keys(a)) {
                    a[key] = new classs(a[key]);
                }
                return a;
            }
            return new classs(a);
        }
        return a;
    }
}

Declaring the struct as its own struct first would of course circumvent this, but it'd be great to see some sort of fix for this :) Apologies if this has already been posted as an issue, I couldn't see anything obvious when I did a quick skim!