Last active
October 9, 2018 17:40
-
-
Save miguel-leon/ee47b47223a241f9c814f57f189860ac to your computer and use it in GitHub Desktop.
Mappings for enums in typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; }; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(...) | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SizeView.Small == 's' | |
SizePantsMeasure.Small == PantsMeasure(...) | |
SizeView.values == Object.keys(SizeView) == SizePantsMeasure.values == Object.keys(SizePantsMeasure) == ['Small', 'Medium', 'Large'] | |
SizeView.enum_ === SizePantsMeasure.enum_ === Size |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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