Skip to content

Literal field becomes optional in typescript #36

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

Open
jcampbell opened this issue Apr 24, 2023 · 1 comment
Open

Literal field becomes optional in typescript #36

jcampbell opened this issue Apr 24, 2023 · 1 comment

Comments

@jcampbell
Copy link

If I define a property using a Literal with a default value, it shows as optional in typescript. This is similar to #28 but, I think it should be treated differently because the value must be set, even by a client (the property is used as a discriminator in a union).

from typing import Literal
from pydantic import BaseModel


class MyModel(BaseModel):
  my_bool_property: Literal[False] = False

renders into

/* tslint:disable */
/* eslint-disable */
/**
/* This file was automatically generated from pydantic models by running pydantic2ts.
/* Do not modify it by hand - just update the pydantic models and then re-run the script
*/

export interface MyModel {
  my_bool_property?: false;
}
@alythobani
Copy link

alythobani commented Mar 20, 2025

I could be misunderstanding your use case here, but I don't actually think this should be treated differently from #28.

If MyModel is being sent from TypeScript to Python (e.g. as a request), the presence of the default on the Pydantic model means that even if TS doesn't include my_bool_property, it will still be populated as False on the Python side when processing the request data (converting the JSON into a MyModel instance). So in that case, it should be safe to mark my_bool_property as optional on the TS side.

And if it's being used as a discriminator on the TS side and should be required, that sounds like something pydantic2ts wouldn't have direct knowledge of (but a flag to avoid defaulted-fields becoming optional would solve the issue).

But yeah maybe I'm missing something in what you were looking for here.

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

2 participants