Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript assign enum value to another enum value

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

enter image description here

How could I fix this issue?

like image 749
Pathum Kalhan Avatar asked Feb 06 '26 12:02

Pathum Kalhan


1 Answers

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"
like image 57
Robby Cornelissen Avatar answered Feb 08 '26 01:02

Robby Cornelissen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!