Currently, I am utilizing a TypeScript library known as ts-proto, which is responsible for generating TypeScript code.
The resulting generated code resembles the following:
//BasicMessage.ts
export interface BasicMessage {
id: Long;
name: string;
}
export const BasicMessage = {
encode(message: BasicMessage) : Writer {
...
}
fromJSON(object: any): BasicMessage {
...
}
}
as well as
// BasicMessagePlus.ts
export interface BasicMessagePlus {
id: Long;
name: string;
email: string;
}
export const BasicMessagePlus = {
encode(message: BasicMessagePlus) : Writer {
...
}
fromJSON(object: any): BasicMessagePlus {
...
}
}
Due to the fact that this code is generated, modifications cannot be made. Therefore, my objective is to develop a method capable of encoding a type name and an object similar to the following example:
function encode(typeName: string, object: any): Writer {
import(`/path/to/${typeName}`);
return <typeName>.encode(<typeName>.fromJSON(object));
}
let writer1 = encode("BasicMessage", { id: 1, name: "Fake" });
let writer2 = encode("BasicMessagePlus", { id: 1, name: "Fake", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c2a2d27290c2a2d2729622f2321">[email protected]</a>" });
I have attempted various methods involving eval and globalThis without success in achieving the desired functionality. Any assistance would be greatly appreciated!