YanoRyuichi.com/
Wiki
Blog
GitHub
Sandbox
開始行:
* 区分オブジェクト [#l2f5bed7]
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...
};
function feeYenFor(feeTypeName: string): Yen {
const fee = FeeTypeUtil.fee(feeTypeName as FeeType);
if (!fee) {
throw new Error(`Invalid fee type: ${feeTypeName}`);
}
return fee.yen;
}
console.log(feeYenFor('adult'));
console.log(feeYenFor('adult1'));
終了行:
* 区分オブジェクト [#l2f5bed7]
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...
};
function feeYenFor(feeTypeName: string): Yen {
const fee = FeeTypeUtil.fee(feeTypeName as FeeType);
if (!fee) {
throw new Error(`Invalid fee type: ${feeTypeName}`);
}
return fee.yen;
}
console.log(feeYenFor('adult'));
console.log(feeYenFor('adult1'));
ページ名: