Struggling to find a solution for setting default values for instances created by the factory method createLetterMap
...
I don't think the problem lies in 'How to loop over enums' because it seems impossible due to types not being available at run-time. However, I might be missing something regarding string enums?
enum Letter{
A = "A",
B = "B",
E = "E",
I = "I",
}
type Vowl = Letter.A | Letter.E | Letter.I
class LMAP{
test(){}
}
function createLetterMap<T extends Letter>(){
let lmapExtended = new LMAP() as LMAP & {
[key in T]?:string
};
// ?? create default values for keys somehow ??
return lmapExtended;
}
let vowlMap = createLetterMap<Vowl>()
vowlMap[Letter.E] = "Eat" // OK
// vowlMap[Letter.B] = "Bat" // Error! Good!
let defaultVal = vowlMap[Letter.A]; // undefined. Would like it to be populated.
My goal is to use unions of string enums to generate objects with keys that can be used similar to this scenario:
fn(v:Vowl){
...
letterMap[v].someVowlReleatedWork()
...
}
While using Maps is a working alternative, I feel there could be a cleaner way if types are specified correctly...
The current workaround involves creating an array of enums included in the union type and utilizing both the union and the array in the factory method, which doesn't seem ideal:
...
let Vowls = [Letter.A,... ]
createLetterMap<Vowl>(Vowls)