Mypy 无法从 TypedDict.get(Optional[key], str) 推断类型

Mypy can't infer type from TypedDict.get(Optional[key], str)

我在打开问题之前在这里询问,因为我不确定这是否是预期的行为。我的感觉告诉我它与运行时检查有关,但我不确定,

我有这个 MVE

from typing import Optional
from typing_extensions import TypedDict

D = TypedDict("D", {"bar": Optional[str]})


def foo() -> None:
    a: D = {"bar": ""}
    a.get("bar", "").startswith("bar")

mypy 会报错:

Item "None" of "Optional[str]" has no attribute "startswith"

现在很明显,因为 get 的第二个参数是一个字符串,所以 return 有 .startswith,但仍然是错误。我用的是# type:ignore ,还有其他方法吗?

Optional[T] 代表 TNone,所以 a: D = {"bar": None} 会进行类型检查,这就是 a.get("bar", "").startswith("bar") 不能的原因。如果您认为 TypedDict 中的 every 键是可选的,那么 total=False:

D = TypedDict("D", {"bar": str}, total=False)