小编Max*_*hko的帖子

有没有一种优雅的方式在打字稿中拥有值对象?

问题

出于验证目的,我希望在系统的核心中有一些值对象。这些值对象可以是类:

class UserName {
  readonly value: string;

  constructor(value: string) {
    this.value = value.trim();
    if (this.value === '') {
      throw new Error('Empty value');
    }
  }
}

// and use it

userService.updateName({id: 1, name: new UserName('Maxim')});
Run Code Online (Sandbox Code Playgroud)

但它效果不佳,因为每个人都可以在不实例化类的情况下调用该服务,因此无需验证:

userService.updateName({id: 1, name: {value: INVALID_NAME});
Run Code Online (Sandbox Code Playgroud)

我的解决方案

我有一个接口和实用函数来创建不方便手动创建的对象:

interface ValueObject<T extends string, U> {
  readonly type: T;
  readonly value: U;
  readonly DO_NOT_CREATE_MANUALLY: 'DO NOT CREATE THIS MANUALLY!',
}

function ValueObject<T extends string, U>(type: T, value: U): ValueObject<T, U> {
  return {
    type,
    value,
    DO_NOT_CREATE_MANUALLY: 'DO …
Run Code Online (Sandbox Code Playgroud)

architecture domain-driven-design typescript

5
推荐指数
1
解决办法
4938
查看次数