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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With