I want to copy an object and map its properties in a type safe manner. I can describe the resulting type in TypeScript but I'm unable to achieve mapping the properties without casting.
So, consider I have an object that can be described like this:
interface MyObject {
a: number;
b: string;
}
I want to map all of its properties. In fact, I can describe the mapping with TypeScript correctly:
type MappedObject = {[K in keyof MyObject]: {meta: string; value: MyObject[K]}};
I have now extended all of the properties of MyObject
. Fine. Now, the problem is, I can't apply that transformation in a type safe manner:
const object: MyObject = {
a: 42,
b: 'foo',
};
const mapped = Object.fromEntries(
Object.entries(object).map(([k, v]) => [k, {meta: 'bar', value: v}]),
);
doSomethingWithMappedObject(mapped); // error
function doSomethingWithMappedObject(mapped: MappedObject): void {
// ...
}
In my mind, the result of Object.fromEntries(...)
should have been compatible with MappedObject
but it isn't. How can we achieve this, ideally without casting?