In modern typed Python, you can instead use dataclasses, NamedTuples (both in the standard library), attrs or Pydantic (both third-party) to represent structs/records, the latter also providing validation. Still, TypedDicts are helpful when interfacing with older code that uses dicts for heterogeneous data.
My main gripe with them is that different TypedDicts are not compatible with each other. For example, it would be very helpful if a dict with x:str and y:str fields were considered superclasses of dicts with x:str, y:str and z:str like they are in TypeScript, but they aren't. They are considered different types, limiting their usability in some contexts.
When using homogenous dicts, you can still use dict[str, T], and T can be Any if you don't want to type the whole thing. You can use any hashable type instead of str for keys. I often do that when reading JSON from dynamically typed dict[str, Any] to dataclasses.
class X(TypedDict):
x: str
class Y(TypedDict):
y: str
class XYZ(X, Y):
z: str
That should get you the class/superclass relationship that you want, no? from typing import TypedDict
class A(TypedDict):
a: int
b: str
class B(TypedDict):
a: int
b: str
def f(a: A) -> None: pass
b = B(a=1, b='b')
f(B) # mypy error: Argument 1 to "f" has incompatible type "type[B]"; expected "A" [arg-type]
On the other hand, this is legal in Typescript: interface A {
a: number;
b: string;
}
interface B {
a: number;
b: string;
}
function f(a: A) {}
const b: B = {a: 1, b: 'b'};
f(b);
This is most useful when A has a subset of B's attributes, like this (which also doesn't work in Python): interface A {
a: number;
}
interface B {
a: number;
b: string;
}
function f(a: A) {}
const b: B = {a: 1, b: 'b'};
f(b);