OkResponse(TypedDict): result: Literal[0] data: Data class ErrorResponse(TypedDict): result: Literal[1] error: str type Response = OkResponse | ErrorResponse def unwrap[T](res: Response) -> Data: if res["result"] == 0: return res["data"] else: raise Exception(res["error"]) data: list[Response] = [ {"result": 0, "data": ["foo", "bar", "baz"]}, {"result": 1, "error": "ERROR_CODE_123"}, ] for d in data: try: print(unwrap(d)) except Exception as e: print(f"Error!!!! {e}")