Search code examples
pythonpython-typing

Python equivalent to `as` type assertion in TypeScript


In TypeScript you can override type inferences with the as keyword

const canvas = document.querySelector('canvas') as HTMLCanvasElement;

Are there similar techniques in Python3.x typing without involving runtime casting? I want to do something like the following:

class SpecificDict(TypedDict):
    foo: str
    bar: str

res = request(url).json() as SpecificDict

Solution

  • If I understand you correctly, you're looking for typing.cast:

    from typing import cast
    res = cast(dict, request(url))
    

    This will assert to a typechecker that res is assigned to a value that is a dictionary, but it won't have any effects at runtime.