Regrettably, TypeScript interfaces do not physically exist once your program is compiled
An interface serves as a blueprint that outlines the requirements within your application. It sets the guidelines for classes to adhere to. Any classes derived from an interface must adhere to the established structure.
When compiling TypeScript code, interfaces are not directly converted into JavaScript. Instead, they are utilized for type checking purposes, often referred to as "duck typing" or "structural subtyping".
As a result, you cannot directly access interface properties and manipulate them (although using reflection might be a workaround, it's generally discouraged)
One approach is to explicitly specify which fields to include or exclude from your object
For instance, imagine having an object that follows this interface:
interface Foo {
field1: string;
field2: string;
field3: string;
.....
field140: string;
}
In this scenario, you can define the properties to exclude (opting for exclusion when dealing with 127 out of the total 140 fields)
// Note that this isn't specific to mongoose implementation (if utilized),
// but rather illustrates the concept
const FIELDS_TO_EXCLUDE = ["field128", "field129", "field130", ..., "field140"];
productModel.toDTO(){
const documentData = this;
FIELDS_TO_EXCLUDE.forEach(x => delete documentData[x]);
return documentData;
}
This way, upon calling the toDTO
function, you have the flexibility to modify the object by excluding (or including) specific fields as needed