I'm currently working on a function that can map a property from one object to another.
For example, the mapProperty
function can be utilized like this:
mapProperty('_id', 'id', { _id: "arst" } )
. This should result in the type { id: string }
.
The function mapProperty
is defined below. However, I believe that using as unknown as M
is not ideal. Without it, I encounter the following error:
Type
'T & { [x: string]: T[K]; }'
is not assignable to type'M'
.
'M'
could potentially have any unrelated type compared to'T & { [x: string]: T[K]; }'
.
It's also not feasible to define the return value as : { [key: L]: T[K] }
.
Is there a better solution to this problem?
const mapProperty = <T, K extends keyof T, M, L extends keyof M>(
from: K,
to: L,
obj: T,
): M => {
const prop = obj[from];
delete obj[from];
return ({ ...obj, [to]: prop } as unknown) as M;
};
Edit: (I used Николай Гольцев's answer with a slight modification)
I have introduced an additional parameter which is a function responsible for mapping the value of the target property:
const mapProperty = <T, K extends keyof T, L extends string, M = T[K]>(
obj: T,
from: K,
to: L,
fn?: (x: T[K]) => M,
): Omit<T, K> & { [key in L]: M } => {
const prop = fn ? fn(obj[from]) : obj[from];
delete obj[from];
return { ...obj, [to]: prop } as any;
};