Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type having enum values to mimic enum behavior #316

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

stasberkov
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant