定数に複数情報を割り当てる方法について
オブジェクトを使う方法
オブジェクトをつかって基本となる定数に整数または文字列を割り当てます。
例
const STATUS = {
Start: 1,
Complete: 9,
} as const;
この定数の各値に対して以下のようにもう一つオブジェクトを定義して、定数に複数情報を割り当てます。
例
const statusList = {
[STATUS.Start]: { name: "開始", priority: 10 },
[STATUS.Complete]: { name: "完了", priority: 20 },
};
このオブジェクトを使って情報を取り出す関数を定義します。
例 nameを取得する関数
exprot type StatusType = keyof typeof StatusList;
export function getStatusName(status: StatusType): string {
const data = statusList[status];
if (data) {
return data.name;
}
throw new Error(`Invalid status: ${status}`);
}
名前を取得したい場合、getStatusName関数を使って取得します。
const name = getStatusName(STATUS.Complete)
サンプル
export const STATUS = {
Start: 1,
Complete: 9,
} as const;
const statusList = {
[STATUS.Start]: { name: "開始", priority: 10 },
[STATUS.Complete]: { name: "完了", priority: 20 },
};
exprot type StatusType = keyof typeof StatusList;
export function getStatusName(status: StatusType): string {
const data = statusList[status];
if (data) {
return data.name;
}
throw new Error(`Invalid status: ${status}`);
}
export function getStatusPriority(status: StatusType): number {
const data = statusList[status];
if (data) {
return data.priority;
}
throw new Error(`Invalid status: ${status}`);
}