bcherny / json-schema-to-typescript

Compile JSON Schema to TypeScript type declarations
https://bcherny.github.io/json-schema-to-typescript-browser/
MIT License
2.96k stars 393 forks source link

Schema type inference should take `format` into account #528

Open boneskull opened 1 year ago

boneskull commented 1 year ago

I'm not sure if support for the ipv6 format was implemented or if it was intended to be implemented, but using a string prop with an anyOf [{format: 'hostname'}, {format: 'ipv6'}], the result is string and {[key: string]: unknown}, where hostname converts to string.

ipv6 should also convert to string.

ref: https://github.com/appium/appium/pull/18690

bcherny commented 1 year ago

We don't take format into account when inferring a schema's type. Without a full example, I'm not sure why you're getting string at all.

To get string, add "type": "string" to your schema:

{
  "type": "object",
  "properties": {
    "a": {
      "format": "hostname",
      "type": "string"
    }
  }
}

Separately, we should improve type inference to select the appropriate type for common values of format.

boneskull commented 1 year ago

@bcherny Thanks. The code was:

{
  "type": "string",
  "anyOf": [
    {"format": "hostname"},
    {"format": "ipv6"}
  ]
}

Changing it to this solved the problem:

{
  "type": "string",
  "anyOf": [
    {"format": "hostname", "type": "string"},
    {"format": "ipv6", "type": "string"}
  ]
}

So it looks like the type didn't get "inherited". I'm not sure if that's what should be happening?

boneskull commented 1 year ago

though, curiously, hostname did get converted to string, but ipv6 did not. (I can speculate that there's a bug where only the first item in an anyOf inherits its type from its parent)