Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!