Skip to content

Commit 44e527a

Browse files
authored
Fix strict-optional in extending generic TypedDict (#16398)
Fixes #16395
1 parent 3712193 commit 44e527a

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

mypy/semanal_typeddict.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
has_placeholder,
3838
require_bool_literal_argument,
3939
)
40+
from mypy.state import state
4041
from mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type
4142
from mypy.types import (
4243
TPDICT_NAMES,
@@ -203,7 +204,8 @@ def add_keys_and_types_from_base(
203204
any_kind = TypeOfAny.from_error
204205
base_args = [AnyType(any_kind) for _ in tvars]
205206

206-
valid_items = self.map_items_to_base(valid_items, tvars, base_args)
207+
with state.strict_optional_set(self.options.strict_optional):
208+
valid_items = self.map_items_to_base(valid_items, tvars, base_args)
207209
for key in base_items:
208210
if key in keys:
209211
self.fail(f'Overwriting TypedDict field "{key}" while merging', ctx)

test-data/unit/check-typeddict.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3379,3 +3379,20 @@ bar |= d1 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "Di
33793379
bar |= d2 # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "Dict[int, str]"; expected "TypedDict({'key'?: int, 'value'?: str})"
33803380
[builtins fixtures/dict.pyi]
33813381
[typing fixtures/typing-typeddict-iror.pyi]
3382+
3383+
[case testGenericTypedDictStrictOptionalExtending]
3384+
from typing import Generic, TypeVar, TypedDict, Optional
3385+
3386+
T = TypeVar("T")
3387+
class Foo(TypedDict, Generic[T], total=False):
3388+
a: Optional[str]
3389+
g: Optional[T]
3390+
3391+
class Bar(Foo[T], total=False):
3392+
other: str
3393+
3394+
b: Bar[int]
3395+
reveal_type(b["a"]) # N: Revealed type is "Union[builtins.str, None]"
3396+
reveal_type(b["g"]) # N: Revealed type is "Union[builtins.int, None]"
3397+
[builtins fixtures/dict.pyi]
3398+
[typing fixtures/typing-typeddict.pyi]

0 commit comments

Comments
 (0)