Enums
tkrajina opened this issue · 4 comments
Enums support
Do we have any update on this? It would be very interesting if we could also have centralized the enums.
I did try it, but the problem is that this tool uses reflect to find all the field names. Now, reflect can't be used to find all the elements of an enum.
Now, I either implement a code parser to find the elements (including the names and values), or I can expect the user to give all the values.
For example, if the "enum" is defined with:
type Weekday int
const (
Sunday Weekday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
func (w Weekday) TSName() string {
switch (w) {
case Monday: return "MONDAY"
....
}
}
var Weekdays = []Weekday{ Sunday, Monday, ...}
Then it would be simple to add another method to typescriptify:
converter.AddEnumValues(reflect.TypeOf(Weekday{}), AllWeekdays)
But it means you should always have a list of all values and the TSName() (or, maybe, String() as a backup) function defined.
An experimental implementation is in https://github.com/tkrajina/typescriptify-golang-structs/tree/enums
Given:
type Weekday int
const (
Sunday Weekday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
func (w Weekday) TSName() string {
switch w {
case Sunday:
return "SUNDAY"
case Monday:
return "MONDAY"
case Tuesday:
return "TUESDAY"
case Wednesday:
return "WEDNESDAY"
case Thursday:
return "THURSDAY"
case Friday:
return "FRIDAY"
case Saturday:
return "SATURDAY"
default:
return "???"
}
}
var AllWeekdays = []Weekday{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
type Holliday struct {
Name string `json:"name"`
Weekday Weekday `json:"weekday"`
}It will generate:
export enum Weekday {
SUNDAY = 0,
MONDAY = 1,
TUESDAY = 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY = 6,
}
export class Holliday {
name: string;
weekday: Weekday;
}If TSName() is not defined, it will use String(), if that is not defined it will generate enums with VALUE_0...VALUE_6.
The enum must be explicitly defined with:
converter.AddEnumValues(reflect.TypeOf(Weekday(Sunday)), AllWeekdays)...if not. The field will be treated as a number.
Cool thanks, I will check it out!