It seemed very easy but I really cannot make it work. I'm trying to map my object into another object with only nested property. Example:
const child1: Child<string> = { nested: "one" };
const child2: Child<number> = { nested: 2 };
type Child<T> = { nested: T };
const abc = {
child1,
child2
}
const nestedOnly = {
child1: abc.child1.nested,
child2: abc.child2.nested
}
How can I get write a generic function that will take any object as a parameter and return object wit nested properties only without losing particular types? It would work in similar way to Array.map. I tried this:
function get<T>(ac: T){
return Object
.keys(ac)
.reduce((result, currentKey) => {
result[currentKey] = ac[currentKey].nested
return result;
}, {});
}
But it loses typings. I also tried to create mapped type in typescript and cast it inside this function but I couldn't work out how this type should look like.
This is a type I came up with:
type NestedType<T extends typeof abc> = {[P in keyof T]: T[P]['nested']}
It seems to work fine however I need to get rid of typeof abc here because it has to be generic function. Is there a way to say T[P] has to have 'nested' property in this type ?