TypeScriptのコンパニオンオブジェクトパターン
#TypeScript
#デザインパターン
- コンパニオンオブジェクトパターンは、クラスや型に関連する静的メソッドやプロパティをまとめるためのデザインパターンです。これにより、関連する機能を一箇所に集約し、コードの可読性とメンテナンス性を向上させます。TypeScriptでは、クラスと同じ名前のオブジェクトを定義することで、コンパニオンオブジェクトを実現できます。
code: typescript
// Currency.ts
type Currency = {
unit: "EUR" | "GBP" | "JPY" | "USD";
value: number;
};
const Currency = {
DEFAULT: "USD",
from(value: number, unit = Currency.DEFAULT): Currency {
return { unit, value };
}
};
export { Currency };
// index.ts
import { Currency } from "./Currency";
// Use case 1: Used as type
let amountDue: Currency = {
unit: "JPY",
value: 83733.1
};
// Use case 2: Used as factory object
let otherAmountDue = Currency.from(330, "EUR");
console.log({ amountDue, otherAmountDue });