TypeAliasType creates named type aliases with proper semantics.
1# Python 3.12+ syntax2type UserID = int3type JSON = dict[str, any]4type Handler = Callable[[str, int], bool]56# Usage7def get_user(user_id: UserID) -> JSON:8 return {"id": user_id}910def register_handler(handler: Handler) -> None:11 handlers.append(handler)1213# Complex aliases14type Response[T] = dict[str, T]15type Result[T, E] = tuple[T | None, E | None]1617# Usage with generics18def process() -> Response[User]:19 return {"data": User("Alice")}2021def divide(a: int, b: int) -> Result[int, str]:22 if b == 0:23 return (None, "Division by zero")24 return (a // b, None)2526# Pre-3.12 equivalent27from typing import TypeAlias2829UserID: TypeAlias = int30JSON: TypeAlias = dict[str, any]3132# Runtime behavior33print(type(UserID)) # <class 'typing.TypeAliasType'>34print(UserID.__value__) # <class 'int'>
Benefits: