我正在使用类型安全的Typescript创建对象映射器。
我可以使用this playground和此代码在一个层次上深入研究
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
}
但是,如果我想将其设为递归类型,以便每个嵌套键都可以进行转换,则无法获取语法,请尝试以下操作:
type TransformerMap<S> = {
[P in keyof S]?: S[P] extends object
? TransformerMap<S[P]>
: S[P] | ((s: S) => any) | TransformerActions;
};
但这不起作用。
如何以这种方式创建递归类型。
答案 0 :(得分:0)
如果我理解正确,那么这样的事情呢?
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
}
}