Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

246
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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"
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda