Theo's Typesafe CultTTC
Theo's Typesafe Cult12mo ago
5 replies
Xanacas

Typesafe: Is there any better way to write this code?

I always try to get better at coding and a challenge I recently came across is this one: I receive some values from database, give that object to a function, which calculates some additional values and adds them to the object.

I am aware of two ways to do this. The first is using spread operator - which is very handy, but produces (to my understanding) potentially a huge performance impact because every input object gets copied to be spread.
function calculateSums(project: InputProject)
const budgetEuros = project.workstreams.reduce((acc: number, workstream) => acc + workstream.budgetEuros, 0);
return {
    ...project,
    budgetEuros
}


I tried to avoid this but ended up with a huge amount of code just to satisfy typescript.

type InputProject = Awaited<ReturnType<typeof fetchProjects>>[number];
type OutputProject = InputProject & {
    budgetUsedHours: number;
};
type OptionalProject = InputProject & {
    budgetUsedHours?: number;
};

function calculateSums(project: InputProject): OutputProject {
    const p = project as unknown as OptionalProject;

    p.budgetUsedHours= p.workstreams.reduce((acc: number, workstream) => acc + workstream.budgetHours, 0);

    return p as unknown as OutputProject;
}


Is there any better way to write this code?
Was this page helpful?