assemblyscript icon indicating copy to clipboard operation
assemblyscript copied to clipboard

Support string enums

Open MaxGraey opened this issue 6 years ago • 5 comments

enum Weekend {
  Friday = 'FRIDAY',
  Saturday = 'SATURDAY',
  Sunday = 'SUNDAY'
}

MaxGraey avatar Mar 26 '19 14:03 MaxGraey

I'm interested in working on this feature. Any guidance as to what would be a good place to start?

Also, do we want to support something like this -

enum BooleanLikeHeterogeneousEnum {
    No = 0,
    Yes = 'YES',
}

nischayv avatar May 07 '20 21:05 nischayv

Also, do we want to support something like this

I think yes. Actually enum is just another variant of grouped constants under same namespace, so BooleanLikeHeterogeneousEnum.No should just replace to 0 and BooleanLikeHeterogeneousEnum.YES to 'YES'.

@dcodeIO wdyt?

MaxGraey avatar May 07 '20 21:05 MaxGraey

Type-wise the compiler currently assumes that var a: SomeEnum is i32. As such, mixing different kinds of values appears problematic in about the same way union types are. Pure string enums should be possible in the same way

namespace Weekend {
  const Friday = 'FRIDAY';
  const Saturday = 'SATURDAY';
  const Sunday = 'SUNDAY';
}
type Weekend = string;

is. How important would you say string enums are over this syntax?

dcodeIO avatar May 08 '20 08:05 dcodeIO

Removing the good first issue label here, because this might become quite tricky. Not super tricky, but potentially too tricky for a very first issue.

dcodeIO avatar May 29 '20 11:05 dcodeIO

Just a note, for the above workaround compiles, but for it to not show as TypeScript errors (ie., in VS Code), the constants have to be exported from the namespace.

namespace Weekend {
  export const Friday = 'FRIDAY';
  export const Saturday = 'SATURDAY';
  export const Sunday = 'SUNDAY';
}
type Weekend = string;

Additionally, if you need to export it from the file it's declared in, you need to export both the namespace and the type, or you do get an AssemblyScript compiler error.

export namespace Weekend {
  export const Friday = 'FRIDAY';
  export const Saturday = 'SATURDAY';
  export const Sunday = 'SUNDAY';
}
export type Weekend = string;

It's still not a great solution, because the variable is still just a string and can take any value, not just the ones declared.

mattjohnsonpint avatar Jun 21 '24 17:06 mattjohnsonpint