'How to use maps and enumerations for property names in typescript?
The object pulsarAlert
is returning with type [x: string] : string
Ideally it should be able to detect that if channel = "SMS"
then notificationType = "phone"
, if channel = "Email"
then notificationType = "email"
.
This closed set of possibilities may be asking too much from typescript.
I know typescript understands if conditions but does not appear to close the scope of [notificationType]
at the time of assignment.
return notificationChannels.map((channel) => {
const notificationType = channelToProperty[channel];
const contactInfo = user[notificationType];
const pulsarAlert = {
alertType,
alertMessage,
notificationChannel: channel,
[notificationType] : contactInfo
};
return pulsarAlert;
});
export enum NotificationChannels {
"SMS"="SMS",
"Email"="Email"
}
export enum NotificationProperties {
"phone"="phone",
"email"="email"
}
export const channelToProperty = {
[NotificationChannels.SMS]: NotificationProperties.phone,
[NotificationChannels.Email]: NotificationProperties.email,
}
export interface MessagePayload {
alertMessage: string;
alertType: string;
}
export interface EmailEventPayload extends MessagePayload {
[NotificationProperties.email]: string;
notificationChannel: NotificationChannels.Email
}
export interface SmsEventPayload extends MessagePayload {
[NotificationProperties.phone]: string;
notificationChannel: NotificationChannels.SMS
}
export type MessageForPulsar = EmailEventPayload | SmsEventPayload;
pulsarAlert
should end up being of type MessageForPulsar
Solution 1:[1]
Typescript doesn't know that you want the newly created pulsarAlert
to be that type - it will infer the type from it's assignment.
If you want to type it then you should assign a type to the variable, e.g. const pulsarAlert: MessageForPulsar = { ... }
, or assign a return type to your map, e.g. .map<MessageForPulsar>(...)
so that Typescript will complain if you try to return something that cannot be cast to that type. You may also need to ensure your other variables have the correct types too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | PAB |