首页 > 其他分享 >[Typescript] Restrict available operations on values using value objects

[Typescript] Restrict available operations on values using value objects

时间:2024-07-29 14:39:29浏览次数:15  
标签:available operations Typescript Money private currency amount __ type

Value Objects are another pattern in Domain-driven Design that provide more structure around what you can and cannot do with a type.

In TypeScript we create Value Objects with classes that will define what operations can be performed to the value on the class itself. In this lesson we'll explore how to create a Value Object for our Money type.

 

declare const __brand_type__: unique symbol
type Branded<BrandType, BrandName> = BrandType & {
  readonly [__brand_type__]: BrandName
}
type Currency = "USD" | "EUR"
type Money = Branded<number, "MONEY">

class Money {
  constructor(
    private amount: Money,
    private currency: Currency
  ) {}
    
  add(another: Money) {
    if (this.currency != another.currency) {
      throw new Error(`Cannot add different currencies`);
    }
    return new Money(
      this.amount + another.amount,
      this.currency
    );
  }

  multiply(factor: number) {
    return new Money(this.amount * factor, this.currency);
  }
}

 

Due to definitly assign problem for constructor, you cannot restrict object creation by using constructor. One way to do it is using static from method.

  1. change constructorto private
  2. add static frommethod
declare const __brand_type__: unique symbol
type Currency = "USD" | "EUR"

class Money {
  private constructor(
    private amount: number,
    private currency: Currency
  ) {}
    
  static from(amount: number, currency: Currency) {
    if (amount <= 0) {
      throw new Error(`Cannot add different currencies`)
    }
    return new Money(
      this.amount + another.amount,
      this.currency
    )
  }
    
  add(another: Money) {
    if (this.currency != another.currency) {
      throw new Error(`Cannot add different currencies`);
    }
    return new Money(
      this.amount + another.amount,
      this.currency
    );
  }

  multiply(factor: number) {
    return new Money(this.amount * factor, this.currency);
  }
}

 

标签:available,operations,Typescript,Money,private,currency,amount,__,type
From: https://www.cnblogs.com/Answer1215/p/18330030

相关文章

  • typescript: vscode create project
       npmcreatevue@latestcdvue-projectnpmi-Dtypescriptnpminstall-gtypescriptts-nodenpminstallwebpack-gnpminstall-g@vue/clinpminstall-gtypescripttsc--versionnpminstall--gcreate-vueornpminstall--g@vue/clinp......
  • 如何在 vercel 部署中路由 python 和 typescript 无服务器函数
    我从一个带有Next.js和Typescript前端以及python后端的全栈应用程序开始。由于我们想在vercel上部署,因此我们将所有后端功能迁移到/api文件夹中的typescript函数中,可通过以下方式访问:fetch('api/**foldername**)问题是我有一个简单的pytorch模型,因此......
  • React+TypeScript 组件库开发全攻略:集成Storybook可视化与Jest测试,一键发布至npm
    平时我除了业务需求,偶尔会投入到UI组件的开发中,大多数时候只会负责自己业务场景相关或者一小部分公共组件,极少有从创建项目、集成可视化、测试到发布的整个过程的操作,这篇文章就是记录组件开发全流程,UI组件在此仅作为调试用,重点在于集成项目环境。组件我们使用React+TypeScri......
  • TypeScript与面向对象编程
    引言TypeScript简介TypeScript是JavaScript的一个超集,由微软开发,它在JavaScript的基础上添加了类型系统和对ES6+的新特性的支持。TypeScript最终会被编译成纯JavaScript代码,以便在任何支持JavaScript的环境中运行。面向对象编程(OOP)概念面向对象编程是一种编程范式,它使用“......
  • TypeScript体操(一):从基础到进阶
    目录前言UtilityTypes是什么?常用UtilityTypes前置知识`typeof``keyof``typeof`和`keyof`的区别`never`关键字`extends`关键字结合条件判断`infer`类型推断(模式匹配)判断是与非判断两个类型是否相等或兼容循环递归嵌套字符串数组协变(Covariance)逆变(Contravarian......
  • 如何从“.d.ts”文件生成 TypeScript API 文档?
    如何从.d.ts文件生成typescriptAPI文档?我尝试typedoc传输这个库:%npxtypedocindex.js[warning]Theentrypoint./index.jsisnotreferencedbythe'files'or'include'optioninyourtsconfig[error]Unabletofindan......
  • 服务启动报错: [ main] c.a.n.c.config.http.ServerHttpAgent : no available server
    场景:一个服务,注册中心使用nacos 服务启动时报错:2024-07-1913:11:17.466ERROR32188---[main]c.a.n.c.config.http.ServerHttpAgent:[NACOSSocketTimeoutExceptionhttpGet]currentServerAddr:http://localhost:8848,err:connecttimedout2024-07-1913:11:18.......
  • npm/yarn/pnpm install失败:ERR_PNPM_NO_VERSIONS No versions available for uWebSock
    ERR_PNPM_NO_VERSIONS NoversionsavailableforuWebSockets.js.Thepackagemaybeunpublished.我在新项目中想要切换包管理器从yarn到pnpm的时候,删除node_modules和yarn.lock之后,pnpminstall竟然提示这个包可能没发布。我觉得这个不可能,都需要使用了,怎么可能没发......
  • TS 入门(七):TypeScript模块与命名空间
    目录前言回顾泛型编程1.模块a.导入和导出b.默认导出c.重命名导入和导出2.命名空间a.定义命名空间b.嵌套命名空间3.动态导入与条件导入a.动态导入b.条件导入结语前言在前几章中,我们学习了TypeScript的基础知识、函数与对象类型、接口与类、以及泛型编......
  • TypeScript
    TypeScriptTypeScript简介使用ts类型注解JS已有类型TS新增类型Typescript高级类型TypeScript简介1.ts是js的超集,在js的基础上,添加了类型支持(:表示)2.ts属于静态类型(编译期做类型检查)的编程语言,减少不同类型的赋值错误(意外行为),js属于动态类型(执行期进行类型检查)3.......