代码之家  ›  专栏  ›  技术社区  ›  Arnaud Denoyelle

避免混淆2种不同的ID类型

  •  2
  • Arnaud Denoyelle  · 技术社区  · 2 年前

    我的客户有两个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) {}
    

    知道吗?

    1 回复  |  直到 2 年前
        1
  •  3
  •   Matthieu Riegler    2 年前

    TS使用 structural typing .

    如果你想区分这些类型,你必须依赖 branded types .

    export type CustomerId = string & {__brand : 'customerId' };
    export type UserId = string & {__brand : 'userId' };
    
    推荐文章