Allow `Unpack[TypeDict]` to accept undefined keys (via new setting)

Right now, when calling Unpack[TypedDict(total=False)], there is zero flexibility to allow the user to provide kwargs that are outside the definition of the typed dict.

There are, however, situations where developers want to use the TypeDict to give type hinting for a set of kwargs that are known to exist, but also allow for the user to define any kwargs that are not statically defined.

The example below gets us 90% of the way there:

class VdomAttributes(TypedDict, total=False):
    accessKey: str
    aria_hidden: str
    className: str
    dangerouslySetInnerHTML: dict[str, str]
    draggable: bool
    hidden: bool | str
    htmlFor: str
    inputMode: str
    itemProp: str
    style: dict[str, str | int | float]

@overload
def react_component(**props: Unpack[GenericPropsTypedDict]) -> None: ...

@overload
def react_component(**props: Any) -> None: ...

def react_component(**props: Any) -> None: ...

With the example above, we get IDE auto-completion for any keys within GenericPropsTypedDict. However, since it utilizes an overload with Any, type checking no longer occurs for any kwargs.

To resolve this situation, I would propose another initialization argument that allows for undefined keys to be accepted. I would speculate it to have a name similar to allow_any, so that’s what I’ve included in my example below.

class VdomAttributes(TypedDict, total=False, allow_any=True): ...

def react_component(**props: Unpack[GenericPropsTypedDict]) -> None: ...

PEP-728 already solves this problem, with extra_keys=Any and more flexibility, like e.g. specifying that all the unknown keys need to have a certain type.

2 Likes