Skip to content

Instantly share code, notes, and snippets.

@miguel-leon
Last active October 9, 2018 17:40
Show Gist options
  • Save miguel-leon/ee47b47223a241f9c814f57f189860ac to your computer and use it in GitHub Desktop.
Save miguel-leon/ee47b47223a241f9c814f57f189860ac to your computer and use it in GitHub Desktop.
Mappings for enums in typescript
export class EnumMap<E, T> {
values: string[];
enum_: E;
private constructor(enum_: E, mappings: EnumMap.Type<E, T>) {
this.values = Object.keys(mappings);
this.enum_ = enum_;
return Object.assign(Object.create(this), mappings);
}
static of<E, T>(enum_: E, mappings: EnumMap.Type<E, T>): EnumMap<E, T> & EnumMap.Type<E, T> {
return new EnumMap<E, T>(enum_, mappings) as (EnumMap<E, T> & EnumMap.Type<E, T>);
}
}
export namespace EnumMap {
export type Type<E, T> = { [P in keyof E]: T; };
}
enum Size {
Small, Medium, Large
}
// one mapping to string
const SizeView = EnumMap.of(Size, {
Small: 's',
Medium: 'm',
Large: 'l'
});
class PantsMeasure {
constructor(public waist: number,
public hips: number,
public rise: number,
public inseam: number,
public cuff: number) {
}
}
// a second mapping, now to PantsMeasure
const SizePantsMeasure = EnumMap.of(Size, {
Small: new PantsMeasure(...),
Medium: new PantsMeasure(...),
Large: new PantsMeasure(...)
});
SizeView.Small == 's'
SizePantsMeasure.Small == PantsMeasure(...)
SizeView.values == Object.keys(SizeView) == SizePantsMeasure.values == Object.keys(SizePantsMeasure) == ['Small', 'Medium', 'Large']
SizeView.enum_ === SizePantsMeasure.enum_ === Size
enum E {
A, B
}
type KeysAB = { [P in keyof typeof E] };
type Keys01 = { [P in E] };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment