I have a method called saveTask
type Task = string;
enum Priority {
Low = "Low",
Medium = "Medium",
High = "High",
}
enum Label {
Low = "Low",
Med = "Med",
High = "High",
}
interface Item {
task: Task;
priority: Priority;
}
const saveTask = ({ task, priority }: Item) => {
const id = Date.now();
let label: Label;
if (priority === "Medium") {
label = Label.Med;
} else {
label = priority;
}
// dispatch(addItem({ task, priority, id, isActive: true, label }));
// handleClose();
};
In here `priority is a value which is equal to "Low", "Medium" or "High" Based on the priority I create an additional property called a label. The label could be "Low", "Medium" or "High"
In the else block when I try to say
label = priority
This gives me an error

How could I fix this issue?
It's not the cleanest design, but you can force the compiler's hand:
type Task = string;
enum Priority {
Low = "Low",
Medium = "Medium",
High = "High",
}
enum Label {
Low = "Low",
Med = "Med",
High = "High",
}
interface Item {
task: Task;
priority: Priority;
}
const saveTask = ({ task, priority }: Item) => {
const id = Date.now();
let label: Label;
if (priority === Priority.Medium) {
label = Label.Med;
} else {
label = Label[Priority[priority] as keyof typeof Label];
}
console.log(label);
};
saveTask({task: 'test', priority: Priority.Low}); // "Low"
saveTask({task: 'test', priority: Priority.Medium}); // "Med"
saveTask({task: 'test', priority: Priority.High}); // "High"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With