ts-proto icon indicating copy to clipboard operation
ts-proto copied to clipboard

Why no namespaces in generated code?

Open renkei opened this issue 2 years ago • 2 comments

I have two (maybe stupid) questions about design decisions. In the generated code I can see that...

1. Package names are not reflected as namespace

Can you explain why the the package name is ignored for scoping messages? Instead, I see a line like

export const protobufPackage = "..."

that is just a string. What is it for? How can this be compared to generated C++ or C# code, where package names are converted to namespaces?

2. Nested enums are not merged as namespace into classes / interfaces

Let's assume:

syntax = "proto3";

message MyEvent
{
  enum Type
  {
    Info = 0;
    Warning = 1;
    Error = 2;
  }
  
  Type type = 1;
}

I would expect MyEvent.Type:

export interface MyEvent {
  type: MyEvent.Type;
}

export namespace MyEvent {
  export enum Type {
    Info = 0,
    Warning = 1,
    Error = 2,
  }
}

but I get MyEvent_Type:

export interface MyEvent {
  type: MyEvent_Type;
}

export enum MyEvent_Type {
  Info = 0,
  Warning = 1,
  Error = 2,
}

What's the advantage of the non-scoped datatype with the underscore in its name? This name is not defined in the proto file and could be confusing.

renkei avatar Aug 22 '21 15:08 renkei

I'd had issues in the past with namespace being AFAICT basically "soft deprecated" within TypeScript, i.e. it was a pre-ESM modules sort of thing, and outputs like Babel don't support it.

Er, maybe "didn't support it", b/c it looks like babel does now:

https://github.com/babel/babel/commit/0a988143290da1208475aed84c0429591df7d0f8

I'm pretty sure my first attempt at the fromJson + toJson methods put them in namespaces (instead of the current consts, which I think is basically syntax sugar for namespaces anyway).

That said, dunno, they still feel slightly unidiomatic, i.e. in JS/TS generally the file is the unit of modularity directly and not a separate/additional notion of namepaces/packages (which in some languages like Java are locked one to one with file names/paths, but in others are not), and at least anecdotally I've not personally seen a lot of namespace usage in TS circles.

So, dunno, that is the original rationale. Not against changing, especially for nested types stuff...

Having the protobufPackage more directly affect the output would likely be a large/hard change.

stephenh avatar Aug 22 '21 19:08 stephenh

at least anecdotally I've not personally seen a lot of namespace usage in TS circles

Except for, you know, TS itself. ;)

pauldraper avatar Oct 28 '21 15:10 pauldraper