简体   繁体   English

typescript 中的递归 object 映射器类型

[英]recursive object mapper type in typescript

I am creating an object mapper in typescript that is typesafe.我正在 typescript 中创建一个类型安全的 object 映射器。

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 .查看操场示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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