The problem is that I want to use a new type as key for a dictionary but I want to dynamically generate the entries using a loop. But I will prefer not to use ? operator because I know I'll fill all keys and I don't want to force ! evaluation for each call.
const studentList = [
A,
B,
C,
// many many students
] as const;
type Students = typeof studentList[number];
// class Info(); // some properties like grades and teacher
const studentInfo: { [key in Students]: Info }; // won't work const must be initialized
const studentInfo: { [key in Students]: Info } = {}; // won't work as all keys are not defined
const studentInfo: { [key in Students]?: Info } = {}; // I want to avoid ?
for (let name of Students) {
// get info from some db
{ grade, teacher } = lookUp(name)
// initialize dictionary keys
studentInfo[name] = Info(grade, teacher);
}
studentInfo.A!.name; // I want to avoid !
Is there anyway to use the key itself to generate the dictionary so that the type signatures checkout. Maybe something like const studentInfo = { key for key in Students | .... };
. And the reason I feel this should work out is because the compiler can reason that all the keys of the type have been used to create the dictionary.
Is this possible in some way?
I previously asked a version of this question with enums, but thanks to this answer I realized a new type might be better and hit this new question :).