Currently, I am in need of generating a list of constants. For instance,
const Days = {
YESTERDAY: -1,
TODAY: 0,
TOMORROW: 1,
}
I am looking for a method to restrict the types of all properties within Days
. In other words, if I attempt to add a property like BAD_DAY: true
, I want the compiler to raise an error.
To tackle this, I initially tried creating something along the lines of
type ObjectOf<T> = {[k: string]: T};
const Days: ObjectOf<number> = {
A: true;
}
This approach does produce an error, but unfortunately, I do not receive type completion suggestions when typing Days.
. This lack of autocompletion is due to defining it as a keyed object type.
It seems that I have to choose between having code completion similar to the first example, or compiler assistance like in the second example. Is there a way to combine both benefits? Ideally, I am aiming for functionality resembling Java Enums, where it is a predefined list of objects sharing the same type.
enum Days{
Today("SUN"), MONDAY("MON"), TUESDAY("TUES"), WEDNESDAY("WED"),
THURSDAY("THURS"), FRIDAY("FRI"), SATURDAY("SAT");
private String abbreviation;
public String getAbbreviation() {
return this.abbreviation;
}
Days(String abbreviation) {
this.abbreviation = abbreviation;
}
}