Type hinting is not correct on TypedDict with an or statement
Given the following code:
from datetime import datetime
from typing import TypedDict
class TestError(TypedDict):
message: str
timestamp: str
error_type: str
retry_count: int
invalid_error_type: str | None = None
valid_error_type: str = "test"
# Type hinting works.
dict_example: dict[str, str | int] = {
"message": "Test message",
"timestamp": datetime.now().isoformat(),
"error_type": invalid_error_type or valid_error_type,
"retry_count": 0,
}
# Type hinting does not work.
typed_dict_example: TestError = {
"message": "Test message",
"timestamp": datetime.now().isoformat(),
"error_type": invalid_error_type or valid_error_type, # "Expected type 'str', got 'str | None' instead"
"retry_count": 0,
}
Using the standard `dict` type hint evaluates fine. But using the `typing.TypedDict` derived class gives an error for what is essentially a `None or str` statement which should always evaluate to `str` on the “error_type” attribute. Checking this with mypy reports no errors.
I know I could use `typing.cast` to silence this error, but I'm wondering if there's a more proper resolution to this.
I'm on PyCharm 2025.1, Build #PY-251.23774.444, built on April 15, 2025, Source revision: 75830c4c8b807.
Please sign in to leave a comment.
Hi, this issue requires thorough investigation, please create an issue on YouTrack (https://youtrack.jetbrains.com/issues/PY) and attach all relevant information for quicker resolution.