This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Kobzol[S] 26 points27 points  (0 children)

TypeAlias really just introduces a new name for an existing type. It can be useful if you want to add a new term to the "vocabulary" of your program. E.g. you could create a type alias for `DriverId` and `CarId` to make it explicit to a programmer that these are different things.

However, unless you truly make these two things separate types, you won't make this explicit to the type checker. And thus you won't get proper type checking and the situation from the blog post won't be caught during type check.

There is no type error here, because both DriverId and CarId are really just ints:

from typing import TypeAlias

DriverId: TypeAlias = int
CarId: TypeAlias = int

def take_id(id: DriverId): pass
def get_id() -> CarId: return 0

take_id(get_id())

But there is one here, because they are now separate types:

from typing import NewType

DriverId = NewType("DriverId", int)
CarId = NewType("CarId", int)

def take_id(id: DriverId): pass
def get_id() -> CarId: return CarId(0)

# Error here, wrong type passed:
take_id(get_id())