Issue
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 :
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' };
Answered By - Matthieu Riegler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.