improbable-eng / ts-protoc-gen

Protocol Buffers Compiler (protoc) plugin for TypeScript and gRPC-Web.
Apache License 2.0
1.37k stars 172 forks source link

Add type having enum values to mimic enum behavior #316

Open stasberkov opened 9 months ago

stasberkov commented 9 months ago

Changes

Currently tool generates interface and const to access enum-like values.

  export interface ResultCodeMap {
    RESULT_CODE_SUCCESS: 0;
    RESULT_CODE_PASSWORD_CHANGE_REQUIRED: 1;
    RESULT_CODE_PASSWORD_EXPIRED: 2;
    RESULT_CODE_FAILURE: 101;
  }

  export const ResultCode: ResultCodeMap;

Issue with such approach that you cannot use ResultCodeMap as function argument to restrict argument values. You need to write something like

function sendResultCode(code: shared_1.Historical.ResultCodeMap[keyof shared_1.Historical.ResultCodeMap]): void {
...
}

Then you will get compile time checks for input value. Such approach works but not user-friendly. I suggest generating alias for types like shared_1.Historical.ResultCodeMap[keyof shared_1.Historical.ResultCodeMap] and give it name like original enum const.

Type alias shall be

export type ResultCode = ResultCodeMap[keyof ResultCodeMap];

So function and invocation code become

function sendResultCode(code: shared_1.Historical.ResultCode): void {
...
}
...
sendResultCode(shared_1.Historical.ResultCode.RESULT_CODE_SUCCESS);

Such function and call signature naturally mimics regular enum usage.

Verification

Tested in my own project.