Home > front end >  Creating a sub type with only part of the original types properties in typescript
Creating a sub type with only part of the original types properties in typescript

Time:11-05

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.

CodePudding user response:

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

  • Related