Consider following example.
enum DialogType {
Options,
Help
}
class Dialog {
test() : string {
return "";
}
}
class Greeter {
openDialogs: { [key in DialogType]: Dialog | undefined } = {
0: undefined,
1: undefined
};
getDialog(t: DialogType) {
return this.openDialogs[t];
}
}
const greeter = new Greeter();
const d = greeter.getDialog(DialogType.Help);
if (d) document.write(d.test());
Also in playground
There are 3 issues/questions with it:
- Why I cannot omit properties in my initializer literal, even though I declare properties as '| undefined'
- Why I cannot use 'DialogType.Options' as type key, and have to use hardcoded number instead?
- Why do I have to use 'key in DialogType' instead of 'key: DialogType'? (Or can I? )
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…