You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mypy解包TypedDict时丢失类型,如何保留类型?

解决TypedDict展开后类型丢失的问题

你遇到的是类型检查器对字典展开语法的类型推导限制——{**inp}会被推导成通用的dict[str, object],无法匹配MyDict这个TypedDict类型。下面是几种可行的解决方法:

方法一:使用类型断言

直接把展开后的字典断言为目标TypedDict类型,这是最直接的方式:

from typing import TypedDict

class MyDict(TypedDict):
    foo: int

def test(inp: MyDict):
    # 显式断言写法
    n = {**inp}  # type: MyDict

方法二:编写辅助函数封装复制逻辑

如果需要多次复用,可以写一个专门的函数来复制TypedDict,让类型检查器能正确识别返回类型:

from typing import TypedDict, TypeVar

T = TypeVar('T', bound=TypedDict)

def copy_typeddict(td: T) -> T:
    return {**td}

class MyDict(TypedDict):
    foo: int

def test(inp: MyDict):
    n: MyDict = copy_typeddict(inp)  # 类型检查通过

方法三:直接构造新的TypedDict实例

如果TypedDict的字段不多,也可以直接显式构造新实例,避免展开语法的类型问题:

def test(inp: MyDict):
    n: MyDict = {"foo": inp["foo"]}

本质原因是当前类型检查器(比如mypy)对TypedDict的字典展开语法支持有限,无法自动推导展开后的类型和原TypedDict一致,所以需要通过上述方式手动提示类型信息。

内容的提问来源于stack exchange,提问作者tomitrescak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:15:45