0

Consider following TS type aliases and code:

type VehicleId = string;
type HouseId = string;

function doSomethingWithVehicle(id: VehicleId) {}

const houseId: HouseId = "abc";

doSomethingWithVehicle(houseId);

TS doesn't throw any build error because string is assignable to another string. But I'd want to detect such assignment and throw a build error. What is the most TS-idiomatic way to achieve this? Ideally without any more complex types (e.g. a value class), because such strings are coming from JSON API and they are used directly without any transformation.

zakjan
  • 2,391
  • 1
  • 19
  • 29
  • The duplicate is almost identical to your question, just for numbers, Also this might be helpful https://stackoverflow.com/questions/49557714/make-two-types-different-by-parameter/49557889#49557889. It these do not answer your question let me know and I can reopen or if they were don't forget to upvote :) – Titian Cernicova-Dragomir Jun 11 '18 at 07:02
  • Thanks, now I know what's the correct name for this language feature :) – zakjan Jun 11 '18 at 08:14
  • `type VehicleId = string & { readonly __type: unique symbol };` looks like the best current solution with TS 2.9, no need to specify a brand string. For future, there is a discussion at https://github.com/Microsoft/TypeScript/issues/202 – zakjan Jun 11 '18 at 10:51
  • Yeah `unique symbol` is the current best way to ensure incompatibility, the idea is the same, the type of the brand needs to be updated a bit :) – Titian Cernicova-Dragomir Jun 11 '18 at 11:03

0 Answers0