Andrii Abramov
Andrii Abramov

Reputation: 10783

Value classes / strict typing in TypeScript

Is it possible to define value classes for strict types in TypeScript as it is done in Scala?

Type aliases seems to be ignored by TypeScript "compiler":

export type UserId = number;
export type CarId  = number;

const userId: UserId = 1

const findUser = (userId: UserId) => { ... }
findUser(userId) // OK

const findCar  = (carId: CarId) => { ... }
findCar(userId) // OK too! I would like to prevent such behavior

In Scala we can use value classes (besides strict typing it provides more advantages):

case class UserId(value: Int) extends AnyVal

Upvotes: 0

Views: 124

Answers (1)

CerebralFart
CerebralFart

Reputation: 3490

No, this isn't possible in TypeScript. TS uses structural subtyping (also called duck typing), which means that anything that looks enough like a given type, will be accepted as that type.

In your case, both UserID and CarID are structured as just numbers and can thus be used interchangeably.

Upvotes: 0

Related Questions