Search code examples
pythonpython-typing

what's the advantage of `NewType` over `TypeAlias`?


Consider the following example:


UserId = NewType('UserId', int)
ProductId = NewType('ProductId', int)

But I can also do, the following:

UserId: TypeAlias = int
ProductId: TypeAlias = int

So why should I use NewType over TypeAlias or vice versa? Are they both interchangeable?


Solution

  • Aliases don't distinguish between each other. New types do. Consider this example:

    Meter = NewType('Meter', float)
    Gram = NewType('Gram', float)
    MeterSquared = NewType('MeterSquared', float)
    
    def area(length: Meter, width: Meter) -> MeterSquared:
        return MeterSquared(length * width)
    

    Now area(3, 5) won't type check, nor would area(Meter(3), Gram(5)), but area(Meter(3), Meter(5)) will. If you had defined Meter and Gram as mere type aliases, all three would type check.

    Basically, a NewType is, well, a new type entirely distinct from the "base" type, just with the same underlying representation. A type alias, on the other hand, is just another name for an existing type, and the two are entirely interchangeable.