Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Required Optional (nullable) fields exported as non-nullable with Python 3.10 #27

Open
danelkay93 opened this issue Sep 29, 2022 · 1 comment

Comments

@danelkay93
Copy link

From Python 3.10 onwards Type | None is supposed to be preferred over Optional[Type]

pydantic's documentation gives a Python 3.10+ code example for a Required field which is also "Optional" (can receive None as a value).

Versions

  • Python 3.10.4
  • pydantic 1.10.2
  • pydantic-to-typescript 1.0.10:
  • json-schema-to-typescript 1.2.2 (note: "strictNullChecks": true is set in the library's tsconfig.json)

To Reproduce

  1. Define the following pydantic model:
from pydantic import BaseModel, Field

class ExampleItem(BaseModel):
    nullable: str | None
    optional: Optional[str]
    required_nullable: str | None = ...
    required_nullable_alternate: str | None = Field(...)
  1. Export ExampleItem with pydantic2js and receive the result:
export interface ExampleItem{
  nullable?: string;
  optional?: string;
  required_nullable: string;
  required_nullable_alternate: string;
}

Expected Result:

export interface ExampleItem{
  nullable?: string;
  optional?: string;
  required_nullable: string | null;
  required_nullable_alternate: string | null;
}

Notes:

Wouldn't tsconfig with strictNullChecks enabled require nullable notation for a Required Optional pydantic field, considering it could contain None?

I'm not well-versed in TypeScript, but from what I understand, it's acceptable to have | null type annotations (if somewhat unusual), and in this case, it would make Python's responses much clearer for those handling them in TypeScript.

Please correct me if I'm mistaken, as my knowledge of TypeScript might be lacking.

Thanks for the amazing work on the package, it's incredibly useful!

@danelkay93
Copy link
Author

This seems to be an unresolved issue in pydantic with BaseModel.schema_json and the JSON Schema specification it supports. There are multiple workarounds mentioned in the issue I linked

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant