How to get a type from a TypeDict property?

I’ve a TypedDict that I want to reuse its types from:

class MyType(TypedDict):
  x: int
  y: float

def myxfn(a:MyType.x)
   #...


def myyfn(a:MyType.y)
   #...

The TypedDict is much more complex. I want to do it this way, so that if I change the logic of MyType, I get typehints when developing, since names or types will mismatch.

Can you suggest a way to do this?

You can’t get the type from the TypedDict directly. What you can do is define a type alias used by both the typed dict and your function parameter.

XType: TypeAlias = int

class MyType(TypedDict):
    x: XType
    y: float

def myxfn(a: XType):
    ...

It’s more verbose than you probably want, but it preserves the property that one change to XType ensures that MyType and myxfn are both updated properly.

2 Likes

Yeah, I’ve been doing that, and it’s not ideal indeed. Yet, it’s not too bad. Thanks.