I have this type from the d.ts file of an API
type EventConfigurations = {
Event1: {
Enabled?: boolean;
};
Event2: {
Enabled?: boolean;
};
Event3: {
Enabled?: boolean;
};
};
Now that I have this data coming back from the response of that API call
const eventConfigurations: EventConfigurations = {
Event1: { Enabled: true },
Event2: { Enabled: false },
Event3: { Enabled: true }
};
and now I want to map the data to
enum EventDesc {
Event1 = "XXX",
Event2 = "YYY",
Event3 = "ZZZ"
}
type MyEvent = {
eventDesc: EventDesc;
topic: EventTopic;
};
const eventConfigurations: EventConfigurations = {
Event1: { Enabled: true },
Event2: { Enabled: false },
Event3: { Enabled: true }
};
const events: MyEvent[] = (Object.keys(eventConfigurations) as Array<
keyof EventConfigurations
>)
.map(
(eventType) =>
eventConfigurations[eventType].Enabled &&
({
eventDesc: EventDesc[eventType],
topic: EventTopic[eventType]
} as MyEvent)
)
.filter(Boolean);
And the compiler raised an error saying that, the events could be either
(false | MyEvent | undefined)[]
But I added .filter(Boolean); at the end of the map, it should eliminate the possibilities of it being either false or undefined.
Here is the live demo https://codesandbox.io/s/thirsty-yonath-ttdhn?file=/src/index.ts