datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

TypedDict Generation not covering `const` `required`

Open Mazyod opened this issue 9 months ago • 0 comments
trafficstars

Describe the bug Generating TypedDict definitions of a schema with const and required yields NotRequired[str].

To Reproduce

Example schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "AndType": {
      "additionalProperties": false,
      "description": "...",
      "properties": {
        "kind": {
          "const": "and",
          "type": "string"
        }
      },
      "required": [
        "kind"
      ],
      "type": "object"
    }
  }
}

Used commandline:

$ datamodel-codegen \
  --input ./schema.json \
  --output ./schema.py \
  --output-model-type "typing.TypedDict" \
  --target-python-version "3.11"

Generated code:

# generated by datamodel-codegen:
#   filename:  schema.json
#   timestamp: 2025-02-09T17:42:53+00:00

from __future__ import annotations

from typing import Any, NotRequired, TypedDict

Model = Any


class AndType(TypedDict):
    kind: NotRequired[str]

Expected behavior Generate kind: Literal["and"] since it is a required const property.

Version:

  • OS: macOS
  • Python version: 3.13.1
  • datamodel-code-generator version: 0.27.2

Mazyod avatar Feb 09 '25 17:02 Mazyod