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

TypeScript better expression of enums #2105

Closed
baywet opened this issue Dec 22, 2022 · 1 comment · Fixed by #3862
Closed

TypeScript better expression of enums #2105

baywet opened this issue Dec 22, 2022 · 1 comment · Fixed by #3862
Assignees
Labels
enhancement New feature or request TypeScript Pull requests that update Javascript code WIP
Milestone

Comments

@baywet
Copy link
Member

baywet commented Dec 22, 2022

We're currently generating enums like that

export enum BodyType {
    Text = "text",
    Html = "html",
}

Which transpiles down to

export var BodyType;
(function (BodyType) {
    BodyType["Text"] = "text";
    BodyType["Html"] = "html";
})(BodyType || (BodyType = {}));

We should probably instead consider generating this

const BodyTypeConst = {
   Text: "text",
   Html: "html",
} as const;

export type BodyType = keyof typeof BodyTypeConst;

Not only this allows consumers to use the string literal and the symbol interchangeably, it results in this

const BodyTypeConst = {
    Text: "text",
    Html: "html",
};
export {};
@baywet baywet added enhancement New feature or request TypeScript Pull requests that update Javascript code labels Dec 22, 2022
@baywet baywet added this to the Kiota post-GA milestone Dec 22, 2022
@baywet baywet assigned koros and unassigned nikithauc Feb 24, 2023
@github-project-automation github-project-automation bot moved this to Todo in Kiota Apr 25, 2023
@baywet baywet modified the milestones: Backlog, Kiota v1.10 Nov 3, 2023
@koros
Copy link
Contributor

koros commented Nov 6, 2023

@baywet I have made some local changes and from initial observation it looks like the serializer/de-serializer has to be modified as well e.g.

// Sample enum
const BodyTypeConst = {
   Text: "text",
   Html: "html",
} as const;

type BodyType = keyof typeof BodyTypeConst;
// End of sample enum


// utility function to convert to proper casing
function toFirstCharacterUpper(str: string) {
  if (!str) return str;
  return str.charAt(0).toUpperCase() + str.slice(1);
}


// JsonParseNode function getEnumValue 
function getEnumValueByKey<T extends Record<string, unknown>>(enumObject: T): T[keyof T] | undefined {
  const _key = "foo"; // get the actual key
  if (_key in enumObject) {
    return enumObject[_key] as T[keyof T];
  }
  return undefined;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request TypeScript Pull requests that update Javascript code WIP
Projects
Archived in project
Development

Successfully merging a pull request may close this issue.

4 participants