pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

`.get(key, "literal")` on a non-required key with `TypedDict` resolves to `key_type | str`

Open Jackenmen opened this issue 5 months ago • 3 comments

Describe the Bug

Using .get() on a non-required key in a typed dict with a literal value passed as default resolves to a union of that key's type and str rather than a union of that key's type and a literal:

from typing import Literal, NotRequired, TypedDict


class Example(TypedDict):
    key: NotRequired[Literal["value1", "value2"]]


def func(data: Example) -> None:
    reveal_type(data.get("key", "value2"))
    reveal_type(data["key"])
INFO sandbox.py:9:16-43: revealed type: Literal['value1', 'value2'] | str [reveal-type]
INFO sandbox.py:10:16-29: revealed type: Literal['value1', 'value2'] [reveal-type]

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN0AZCAxiVUUADR0AcrgYAlGAEcArhEoxMUgCrNNAEQgBjBgB10580aio4cOgFF8qbrAAUu4geMMAlInM6ILoAaxhSRBk5RVV1TQBtIRExKHjTEAA3cRUYAEZ0qXSsqByAJnSAXQrLCywYMDowFXQjN0xUBlRIpxdiWF86AFoAPij0GAD0YLoNDJhxAH0mLzaO1EI2GAY3dLDSAroi7JhykF9fQODZ%2BaglvVXOtJA9yov0EAkQMg0wKFJCBi0KAUADEdAACqQfn86GgsHh8HQjLh0JA2CoxAwICjCOYwQBlGAwOgACwYDGIcEQAHpqd96n9CLw2NSYOhqZhcEY4NTkaiIOjMdj2Y1eHRUFloKhsLAkSi0RiOsK6LhiFiUXBcegyAwSSjBnNKHBlQBeQ4gADMhFyp3M8VE1CN1XQzS4PD4mkGmDiJggczoZoA5AL0LwYIHzKGGIMNLENJhBntBqgjEZ4PYgwB3VCUdAR94AX0%2BKaxcwAYtAYBQ4TgCCRyAWgA

(Only applicable for extension issues) IDE Information

No response

Jackenmen avatar Jun 12 '26 13:06 Jackenmen

@yangdanny97 do u mind if i give this a try? I reproduced the literal widening for a non-required TypedDict field and have a small overload fix with a regression test ready.

goutamadwant avatar Jun 13 '26 20:06 goutamadwant

@goutamadwant Assigned, thanks

yangdanny97 avatar Jun 15 '26 19:06 yangdanny97

Thanks for assigning this @yangdanny97 Opened PR: https://github.com/facebook/pyrefly/pull/3831. This PR adds a focused overload fix for TypedDict.get literal defaults and includes a regression test for the reported NotRequired[Literal[...]] case.

goutamadwant avatar Jun 16 '26 02:06 goutamadwant