Reputation: 8949
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());
There are 3 issues/questions with it:
Upvotes: 168
Views: 178538
Reputation: 2502
Here is an example of how to use enum as index in typescript:
enum DialogType {
Options,
Help,
About
}
type Dialog = {
whatever: string;
};
type DialogMap = { [key in DialogType]?: Dialog };
let o: DialogMap = {
[ DialogType.Options ]: { whatever: "1" },
[ DialogType.Help ]: { whatever: "2" }
};
Upvotes: 1
Reputation: 250036
|undefined
does not make a property optional, just means it can be undefined
, there is a proposal to make |undefined
members optional but currently it's not implemented. You need to use ?
after ]
to make all properties optional
{ [key in DialogType]?: Dialog }
You can use the dialog enum values as keys, but they need to be computed properties:
let openDialogs: { [key in DialogType]?: Dialog } = {
[DialogType.Options]: undefined,
};
{ [key: number or string]: Dialog }
is an index signature. Index signatures are restricted to only number
or string
as the key type (not even a union of the two will work). So if you use an index signature you can index by any number
or string
(we can't restrict to only DialogType
keys). The concept you are using here is called mapped types. Mapped types basically generate a new type based on a union of keys (in this case the members of DialogType enum) and a set of mapping rules. The type we created above is basically equivalent to:
let o: { [DialogType.Help]?: Dialog; [DialogType.Options]?: Dialog; }
Upvotes: 286