0

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
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96

1 Answers1

0

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.

CerebralFart
  • 3,336
  • 5
  • 26
  • 29