Add to TypedDict new argument for extra keys

class Foo(TypedDict, extra=True):
    a: int
    b: str

foo = Foo(a=1, b="bar")
foo["c"] = "some other value"  # no mypy/typeshed error
foo["a"] = "mismatch type"  # mypy/typeshed error

Sometimes we have dict with partially typed and we want to use types for known part with all typechecker power, but without false positive warnings for extra part.

1 Like

Seems like a straightforward, helpful, non-breaking change to me.

Similar proposal: Mailman 3 How about adding an additional proerty type to TypeDict - Typing-sig -

It’s been proposed a few times before to provide a spelling for a TypedDict that defines the expected value type for any unknown keys. However no individual has yet had enough motivation to shepherd that feature to a full PEP, as far as I can remember.[1]

From the thread referenced above, Eric Traut put forward a fairly complete proposal here which suggests a syntax like:

class A(TypedDict):
    x: int
    __extra__: str | None

In the above syntax @bomzheg 's original example would look like:

class Foo(TypedDict):
    a: int
    b: str
    __extra__: Any

  1. Presently I don’t have significant motivation myself to shepherd this particular TypedDict feature: The JSON types I model with TypedDicts are used by internal APIs that I fully control, so there are no unknown extra keys in the TypedDicts that I use. Thus there is no need for me to define the types of such unknown keys. ↩︎

1 Like