简体   繁体   中英

recursive object mapper type in typescript

I am creating an object mapper in typescript that is typesafe.

I can get this working at one level deep with this playground and this code

enum TransformerActions { 
  Delete = 'delete',
}

type TransformerMap<S> = { 
  [P in keyof S]?: S[P] extends object
    ? ((s: S) => any) | TransformerActions
  : S[P];
};

interface Name { 
  forename?: string;
  surname?: string;
}

type Person = { currentName: Name, previousNames: Name[] }

const personTransformer1: TransformerMap<Person> = {
  currentName: TransformerActions.Delete
}

const personTransformer2: TransformerMap<Person> = {
  currentName: (s) => s.currentName.forename + ' ' + s.currentName.surname
}

But if I wanted to make this a recursive type so each nested key could have transformations, I can't get the syntax, have tried this:

type TransformerMap<S> = { 
  [P in keyof S]?: S[P] extends object
    ? TransformerMap<S[P]>
  : S[P] | ((s: S) => any) | TransformerActions;
};

But that does not work.

How can I created a recursive type this way.

If I understood properly, what about something like this?

enum TransformerActions {
  Delete = 'delete',
}

type TransformerFunc<T> = (src: T) => Partial<T>

type TransformerMap<S> = {
  [P in keyof S]?: S[P] | TransformerFunc<S[P]> | TransformerActions | TransformerMap<S[P]>;
};

interface Name {
  forename?: string;
  surname?: string;
}

type Person = { currentName: Name, previousNames: Name[], child: Person }

const personTransformer1: TransformerMap<Person> = {
  currentName: TransformerActions.Delete
}

const personTransformer2: TransformerMap<Person> = {
  currentName: {
    forename: TransformerActions.Delete
  },
  child: {
    currentName: (child) => {
      return {
        forename: `${child.forename?.toUpperCase()} ${child.surname?.toUpperCase}`,
        surname: TransformerActions.Delete
      }
    },
    child: TransformerActions.Delete
  }
}

Check out the playground example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM