If I have a data structure containing nested objects, I need to create a type that removes specific keys and flattens certain fields recursively
Input:
{
sys: {
id: string;
};
metadata: {
author: string;
};
fields: {
name: string;
age: number;
father: {
sys: {
id: string;
};
metadata: {
author: string;
};
name: string;
},
siblings: {
sys: {
id: string;
};
metadata: {
author: string;
};
name: string;
}[]
};
}
Desired Output:
{
name: string;
age: number;
father: {
name: string;
};
siblings: {
name: string;
}[];
}
To achieve this, I attempted to create a type that filters out 'sys' and 'metadata' keys and recursively processes the 'fields' key:
type Helper<T extends object> = {
[K in keyof T]: K extends "sys" | "metadata"
? never
: K extends "fields"
? ...
: T[K] extends Array<infer I>
? I extends object
? Helper<I>
: never
: T[K] extends object
? Helper<T[K]>
: T[K];
};