打字稿确保正确的类类型

时间:2021-02-05 17:54:31

标签: typescript

我试图在我的类中强输入我的 ID 属性,但看起来 typescript 并不关心。

static create(id: CustomerWalletID | ProviderWalletID, name: string, owner: CustomerID) {
    return new CustomerWallet(id, {
      name,
      owner,
    });
  }

  private constructor(id: CustomerWalletID, private props: Args) {
    super(id);
  }

如您所见,构造函数期望 CustomerWalletID 并且可以接收 CustomerWalletID | ProviderWalletID 作为参数,这应该会触发编译警告。没有。

这是我的 ID 类:

export class CustomerWalletID extends ValueObject<string> {
  equals(customerWalletID: CustomerWalletID) {
    return customerWalletID.value === this.value;
  }
}

export class ProviderWalletID extends ValueObject<string> {
  equals(providerWalletID: ProviderWalletID) {
    return providerWalletID.value === this.value;
  }
}

export abstract class ValueObject<T> {
  protected readonly _value: T;

  constructor(props: T) {
    this._value = Object.freeze(props);
  }

  get value(): T {
    return this._value;
  }

  public abstract equals(_vo: ValueObject<T>): boolean;
}

我做错了什么?

谢谢

1 个答案:

答案 0 :(得分:1)

是的,这在 TypeScript 中的运行方式与在其他(C#、Java 等)语言中的运行方式不同。 TypeScript 使用“结构化”类型,这意味着如果它们具有相同的属性,它将认为 2 个类是相同的(或兼容的)。因此,如果您想为 ID 实现强类型化,您需要在每个 ID 类中添加一个具有唯一名称的额外属性(我知道这并不漂亮)。

interface CustomerWalletId {
  customerWalletId: string; // not just "Id"
}

interface ProviderWalletId {
  providerWalletId: string; // not just "Id"
}