Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Avoid confusing 2 different ID types

My customers have 2 IDs : userId and customerId, that are both strings (UUIDs) and refer to 2 different objects in the database.

For now, I can easily send a customerId to a function that expects a userId as they are both string and I am not satisfied with this situation as it is error prone.

I had the idea to create some type aliases like this :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export type CustomerId = string;
export type UserId = string;

so my Customer class would look like :

export class Customer {
  id: CustomerId;
  userId: UserId;
}

Unfortunately, I can still send a CustomerId to a function that expect a UserId as both types are considered compatible :

  foo() {
    const userId: UserId = "abc123";
    // This line will compile but I want the compiler to throw an error
    this.bar(userId)
  }

  bar(customerId: CustomerId) {}

Any idea ?

>Solution :

TS uses structural typing.

If you want to distinguish those types you’ll have to rely on branded types.

export type CustomerId = string & {__brand : 'customerId' };
export type UserId = string & {__brand : 'userId' };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading