typescript - 避免混淆两种不同的ID类型
我的客户有两个ID:userId 和 customerId,它们都是字符串(UUID),并且分别对应数据库中的两个不同对象。
目前,我可以轻松地将一个 customerId 发送给一个期望 userId 的函数,因为它们都是 string 类型,但我对这种情况不满意,因为它容易出错。
我有了一个想法,要创建一些类似这样的类型别名:
export type CustomerId = string;
export type UserId = string;
所以我的 Customer 类看起来会是:
export class Customer {
id: CustomerId;
userId: UserId;
}
不幸的是,我仍然可以将 CustomerId 发送到期望 UserId 的函数,因为这两种类型被认为是兼容的 :
foo() {
const userId: UserId = "abc123";
// This line will compile but I want the compiler to throw an error
this.bar(userId)
}
bar(customerId: CustomerId) {}
有什么主意吗?
答案#1
TS 使用结构化类型。
如果你想区分这些类型,你将不得不依赖品牌类型。
export type CustomerId = string & {__brand : 'customerId' };
export type UserId = string & {__brand : 'userId' };
