In the Further Exploration example on TypeScript website they show us a way to replace the type of a property with a different type based on some conditions.
How can we do the same but in a recursive way? i.e. not only map the first level properties, but any nested property that passes the check.
The example:
type ExtractPII<Type> = {
[Property in keyof Type]: Type[Property] extends { pii: true } ? true : false;
};
type DBFields = {
id: { format: "incrementing" };
name: { type: string; pii: true };
};
type ObjectsNeedingGDPRDeletion = ExtractPII<DBFields>;
// type ObjectsNeedingGDPRDeletion = { id: false; name: true; }
What I need:
type DBFields = {
id: { format: "incrementing", foo: { type: string; pii: true } };
name: { type: string; pii: true };
};
type ObjectsNeedingGDPRDeletion = ExtractPII<DBFields>;
// type ObjectsNeedingGDPRDeletion = { id: { format: string; foo: true }; name: true; }
In the
falsecase, you just need to execute another check to see if the type is an object, and then callExtractPiion that property.This will results in:
If you want in the
falsecase the valuefalse, then just replaceT[P]withfalse: