Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Map over a collection to add a property to it to change the type of objects within. How?

Tags:

typescript

I've got a collection of objects of type X and I want to convert them to type Y. Type X and Y are identical except that type Y has some additional properties. So, I loop over the array with a .map and assign the missing property.

This, however throws TypeScript - it does not recognise that the code within the map function is adding the missing property that it is complaining about:

Property 'propName' is missing in type 'UnProcessedType' but required in type 'ProcessedType'.

Here is a playground example of the situation in question.

Code:

type UnProcessedType = {
    ab: string,
    cd: string,
};

type ProcessedType = {
    ab: string,
    cd: string,
    ef: string,
};

const col: UnProcessedType[] = [{ ab: 'a', cd: 'd' }, { ab: 'b', cd: 'd' }, { ab: 'b', cd: 'c' }];

const processedCol: ProcessedType[] = col.map(el => {
    el.ef = 'e';
    return el;
});

console.log(processedCol); // All properties there as expected

What is the conventional way to use Typescript in this situation? Thanks in advance for any guidance/tips!

like image 986
Hemal Avatar asked Oct 30 '25 06:10

Hemal


1 Answers

Unless your code is very performance-critical, I would just go for making a copy of the unprocessed object, and add the new property. This can be done elegantly with an object spread:

const processedCol: ProcessedType[] = col.map(el => ({ ...el, ef: 'f' }));

This also has the benefit of not causing mutations to the input array. Mixing the functional style of using map with the imperative style of mutating the input can be a bit confusing.

like image 93
Jonas Høgh Avatar answered Nov 01 '25 20:11

Jonas Høgh