I have a database table with some values intended as constants:
- id: number
- type: string
- name: string
- hex: string (#000000)
Where id is used as a primary/foreign key reference;
and type is generally just an UPPER_SNAKE_CASE version of name.
I'm trying to write a class to represent the constant type, but I also want it to have some kind of static/enum type for simpler usage like Color.RED. How can I design this better?
enum ColorEnum {
RED = 1,
GREEN = 2,
BLUE = 3
}
class Color<Type extends Exclude<keyof typeof ColorEnum, number>> {
public type: Type;
public name: string;
public readonly hex: `#${string}`;
private constructor(type: Type, name: string, hex: `#${string}`) {
this.type = type;
this.name = name;
this.hex = hex;
}
public static RED = new Color(ColorEnum[1], "Red", "#FF0000");
public static GREEN = new Color(ColorEnum[2], "Green", "#00FF00");
public static BLUE = new Color(ColorEnum[3], "Blue", "#0000FF");
}
I did ask ChatGPT, just for some quick ideas, and it suggested something like this which might be fine
const ColorEnum = {
RED: 1,
GREEN: 2,
BLUE: 3,
} as const;
type ColorEnum = typeof ColorEnum[keyof typeof ColorEnum]; // 1 | 2 | 3
class Color {
public readonly id: ColorEnum;
public readonly type: keyof typeof ColorEnum;
public readonly name: string;
public readonly hex: `#${string}`;
private constructor(id: ColorEnum, type: keyof typeof ColorEnum, name: string, hex: `#${string}`) {
this.id = id;
this.type = type;
this.name = name;
this.hex = hex;
}
static readonly RED = new Color(ColorEnum.RED, "RED", "Red", "#FF0000");
static readonly GREEN = new Color(ColorEnum.GREEN, "GREEN", "Green", "#00FF00");
static readonly BLUE = new Color(ColorEnum.BLUE, "BLUE", "Blue", "#0000FF");
static values(): Color[] {
return [Color.RED, Color.GREEN, Color.BLUE];
}
}