1

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 ?

3
  • When you say "object with only nested property", that sounds right away like you need an interface with just the 'nested' property in it. Then build up from that. I think maybe you are just missing interfaces (use polymorphism). In other words if you have some code that only expects that interface then just pass the object to it as if it were the interface. If course you'll need to 'implement MyNextstedInterface' on the objects, etc, but basically this sounds like you can create interfaces to use in your map types. Commented Nov 26, 2017 at 0:51
  • See Child type, it's the interrface you are talking about, right? Commented Nov 26, 2017 at 0:53
  • wow. ok. my mistake. I think you may be better at TypeScript than me! I didn't even realize 'type' keyword is there nor was i aware yet that it even existed in the language. Commented Nov 26, 2017 at 1:05

1 Answer 1

2

You're very close, I think. I would define it this way:

type NestedType<T extends { [k: string]: { nested: any } }> = {[P in keyof T]: T[P]['nested']}

So the type that T has to extend is something with string keys whose values contain a nested property.

You can verify that NestedType<typeof abc> works and is what you expect. Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.