In this simplified example, we have a concept of tags, each defined by a single character. The "Flags" object accumulates these values based on an enum. The goal is to make the source code explicit, concise, easily refactorable, compiler-verified, and ensure that the object storing the flags is compact for efficient database storage.
class Flags<ENU>{
s: string = "";
set(v: ENU){
this.s += v;
return this;
}
has(v: ENU){
return this.s.includes(v);
}
}
enum TypeAnimal{
Winged = "w",
Legged = "l"
}
let flagsBird = new Flags<TypeAnimal>().set(TypeAnimal.Winged);
The objective is to check for any duplicated values in the enums used in this process. One approach could be passing the type as a parameter in the constructor instead of explicitly as a generic, allowing TypeScript to infer the generic type:
class Flags2<ENU>{
s: string = "";
constructor(enu: ENU){
// Check the values in enu here.
}
set(v: ENU){
this.s += v;
return this;
}
has(v: ENU){
return this.s.includes(v);
}
}
let flagsBird2 = new Flags2(TypeAnimal);
However, this approach leads to an error message:
flagsBird2.set(TypeAnimal.Winged); // Argument of type 'TypeAnimal' is not assignable to parameter of type 'typeof TypeAnimal'.ts(2345)
I've experimented with different combinations of typeof but haven't found a working solution yet. Any suggestions or insights? It seems like there's more for me to explore regarding TypeScript and generics.