Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a sub type with only part of the original types properties in typescript

I have the following typescript definitions:

interface myType {
    A: {
      instance: someInstance,
      ...
    },
    B: {
      instance: someOtherInstance,
      ...
    }
}

I would like to create a type, that takes all of the properties of the myType interface, and produces an object, that accepts the type of the instance from that interface. Something along the lines of these:

type myBasicType<TType> = '...';

const a: myBasicType<myType> = {
   A: '...', // an instance of someInstance here
   B: '...', // an instance of someOtherInstance here
}

Basically, what I need is a functionality, that generates a type based on an interface, where the properties of the original interface are kept intact, but their types are changed to a new type based on a specific property from the original interface.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use mapped types:

class someInstance {
  tag: 'someInstance' = 'someInstance'
}

class someOtherInstance {
  tag: 'someOtherInstance' = 'someOtherInstance'
}

interface myType {
  A: {
    instance: someInstance,
  },
  B: {
    instance: someOtherInstance,
  }
}

type Mapper<T> = {
  [Prop in keyof T]: T[Prop] extends { instance: unknown } ? T[Prop]['instance'] : never
}

// type Result = {
//     A: someInstance;
//     B: someOtherInstance;
// }
type Result = Mapper<myType>

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading