timostamm / protobuf-ts

Protobuf and RPC for TypeScript
Apache License 2.0
1.09k stars 130 forks source link

Generated message classes cannot be subclassed because of missing 'export' #617

Closed ptesavol closed 6 months ago

ptesavol commented 10 months ago

Thank you for the great library! We use it extensively in our Streamr network project

It seems that the generated message classes <message_name>$Type are not subclassable because they are not exported from the generated typescript files. Being able to derive subclasses from the message classes would be very useful when creating decorators or facades for the messages. For example, the PingRequest$Type` in the following snipplet of generated code cannot be subclassed because it as not exported.

// @generated message type with reflection information, may provide speed optimized methods
class PingRequest$Type extends MessageType<PingRequest> {
    constructor() {
        super("PingRequest", [
            { no: 1, name: "requestId", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
        ]);
    }
}
timostamm commented 8 months ago

Hey Petri, apologies for the late response. Subclasses are less useful than expected in generated code. You would be able to subclass a message, but for it to take effect, it needs to be used in all places where the original is used in generated code.

So simply exporting the classes will likely not enable this feature. It would be really fantastic if TypeScript had something like csharp's extensions methods, but we're very unlikely to ever get an exact equivalent because of TypeScript's nature.

Depending on the behavior you want to add, patching the original can be a viable alternative. TypeScript has declaration merging, which lets you extend the types as well. This approach has downsides too, but maybe it would be a good idea to simply give an example in this repository.