- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- ソース を表示
- TypeScript/OOP/区分オブジェクト へ行く。
- 1 (2023-05-17 (水) 08:44:44)
TypeScript/OOP/データ指向プログラミングとOOP
type Yen = { amount: number; currency: string; }; type Fee = { yen: Yen; label: string; }; type AdultFee = Fee; type ChildFee = Fee; enum FeeType { adult = 'adult', child = 'child', } const FeeTypeMapUtil = { create: function (): Map<string, Fee> { const adultFee: AdultFee = { yen: { amount: 1000, currency: 'JPY' }, label: 'Adult', }; const childFee: ChildFee = { yen: { amount: 500, currency: 'JPY' }, label: 'Child', }; return new Map<string, Fee>([ [FeeType.adult, adultFee], [FeeType.child, childFee], ]); } } const feeTypeMap = FeeTypeMapUtil.create(); const FeeTypeUtil = { fee: (feeType: FeeType): Fee | undefined => feeTypeMap.get(feeType), }; function feeFor(feeTypeName: string): Yen { const fee = FeeTypeUtil.fee(feeTypeName as FeeType); if (!fee) { throw new Error(`Invalid fee type: ${feeTypeName}`); } return fee.yen; } console.log(feeFor('adult')); console.log(feeFor('adult1'));