evestera / json_typegen

Tools and libraries to create types for Rust, Kotlin, TypeScript and Python from JSON samples
https://typegen.vestera.as
Apache License 2.0
268 stars 26 forks source link

Distinction between nullable and optional #38

Open GerritPlehn opened 1 year ago

GerritPlehn commented 1 year ago

Hi! Similar to #21 when using this library to generate TS types, it's often useful to make a distinction between nullable and optional fields. I'm looking for feedback on this PR as I'm very new to Rust. Currently not all tests are passing and before investing more time I'd like to know if the approach I took is ok.

Input

{
  "a": [{ "nullable": 1 }, { "nullable": null }],
  "b": [
    {
      "optional": 1,
      "always": true
    },
    {
      "always": true
    }
  ],
  "c": [
    {
      "optionalNullable": 1,
      "always": true
    },
    {
      "optionalNullable": null,
      "always": true
    },
    {
      "always": true
    }
  ]
}

Before the changes

export interface A {
    nullable?: number;
}

export interface B {
    optional?: number;
    always: boolean;
}

export interface C {
    optionalNullable?: number;
    always: boolean;
}

After the changes

export interface A {
    nullable: number | null;
}

export interface B {
    optional?: number;
    always: boolean;
}

export interface C {
    optionalNullable?: number | null;
    always: boolean;
}
evestera commented 1 year ago

Thank you for the PR. Looks reasonable at first glance, but it's been a while since I worked on this project, so will need to re-familiarize myself with the project a bit before I consider merging.