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
相关产品推荐
相关产品推荐

