我的客户有两个ID:
userId
和
customerId
,它们都是字符串(UUID),并引用数据库中的两个不同对象。
现在,我可以很容易地发送
客户号
到期望的函数
userId
因为它们都是
string
我对这种情况不满意,因为它很容易出错。
我有了创建一些类型别名的想法,如下所示:
export type CustomerId = string;
export type UserId = string;
所以我的客户类看起来像:
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) {}
知道吗?