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

204
Visualizações
How do I work with TypeScript correctly when I need to change a type of a property in an object

I have this class that represents JSON incoming from POST request.

class MilkCarton {
  company: string;
  price: number;
  expiredAt?: string;
  // ...20 more properties
}

Before I store it in my mongoDB database, I want to change the type of expiredAt to Date, so I have another class that represents the schema of the database.

class MilkCartonSchema: {
  company: string;
  price: number;
  expiredAt?: Date;
  // ...20 more properties
}

expiredAt can be null, I want to create an object that copies the object of type MilkCarton but has its expiredAt converted to Date

prepareMilkForDb(milk: MilkCarton): MilkCartonSchema {
  const preparedMilk = {
    ...milk,
  }

  if (milk.expiredAt) {
    preparedMilk.expiredAt = new Date(milk.expiredAt)
  }

  return preparedMilk;
}

But I run into an error because preparedMilk has already inferred its type and has expiredAt as string, it can't be turned into Date from TypeScript perspective if it's string. But I want it to turn into Date, what is the approach to do that correctly in TypeScript?

EDIT: I ended up going with:

prepareMilkForDb(milk: MilkCarton): MilkCartonSchema {
  const preparedMilk = {
    ...milk,
    ...(milk.expiredAt && {
      expiredAt: new Date(milk.expiredAt)
    }),
  }

  return preparedMilk;
}

This works, but isn't exactly what I wished for, if I had another example with 3 different deep nested ISO string properties that need converting to Date (and backwards) it would be very dirty to do this workaround.

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

0

Does this work for you?

interface MilkCarton {
    company: string;
    price: number;
    expiredAt?: string;
    // ...20 more properties
}

interface MilkCartonSchema {
    company: string;
    price: number;
    expiredAt?: Date;
    // ...20 more properties
}

const prepareMilkForDb = (milk: MilkCarton): MilkCartonSchema => {
    return {
        ...milk,
        expiredAt: milk.expiredAt == null ? undefined : new Date(milk.expiredAt)
    };
}

Typescript sandbox

Note: I changed the classes to interface, I don't know if that's ok or not?

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