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

Python中是否存在TypeScript的Indexed Access Types等价特性?

Python中的Indexed Access Types支持方案

Python的主流类型检查器(如mypy、pyright)已经支持类似TypeScript的Indexed Access Types功能,你可以直接通过泛型参数的属性索引来获取对应类型,无需显式传入第二个泛型参数B。

修改后的代码实现

from typing import TypeVar, Generic, TypedDict

class FieldType(TypedDict):
    pass

class FieldOne(FieldType):
    pass

class FieldTwo(FieldType):
    pass

class MainType(TypedDict):
    item_types: FieldType

class MainOne(MainType):
    item_types: FieldOne

class MainTwo(MainType):
    item_types: FieldTwo

# 绑定A为MainType的子类型,确保它包含item_types属性
A = TypeVar("A", bound=MainType)

class Service(Generic[A]):
    def __init__(self, main_collection: MongoDBCollection):
        self.main_collection = main_collection

    def get_main(self, document_id: str) -> A:
        # 修正原代码中未定义的arg变量,替换为document_id
        return self.main_collection.find_one({'_id': document_id})

    def get_field(self, document_id: str) -> A['item_types']:
        main = self.get_main(document_id)
        return main["item_types"]

# 只需指定MainOne,item_types的类型会自动推导为FieldOne
service = Service[MainOne]()

关键说明

  • 索引语法A['item_types']可以直接提取泛型参数A中item_types键对应的类型,完全替代原代码中B泛型的作用。
  • 该语法需要确保类型检查器版本足够新:mypy需0.910以上,pyright则原生支持。
  • 移除冗余的B泛型参数后,代码更简洁,同时保留了完整的类型安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 00:37:22