Skip to content

Instantly share code, notes, and snippets.

@Mellbourn
Last active November 22, 2022 08:13
Show Gist options
  • Save Mellbourn/17aab6fd5c227a825d10402bd5140399 to your computer and use it in GitHub Desktop.
Save Mellbourn/17aab6fd5c227a825d10402bd5140399 to your computer and use it in GitHub Desktop.
const UP = "Up";
// problem: cannot use constant UP in enum declaration
// problem: generated JavaScript looks like crap
enum mixedEnum {
up = "Up",
one = 1
}
const mixupEnum: mixedEnum = mixedEnum.up;
// problem: cannot assign using string "Up"
// const mixupEnumFail: mixedEnum = UP;
console.log(mixupEnum === UP);
// problem: cannot use constant UP
type mixed = "Up" | "Down" | 1234;
// problem: cannot use mixed.up
const mixup: mixed = UP;
console.log(mixup === UP);
// problem: this is not a type, cannot declare type fakeEnum
const fakeEnum = {
Up: UP,
one: 1
};
const fakeValue = fakeEnum.Up;
console.log(fakeValue === UP);
// export both fakeEnumType and fakeEnum2, use the first as type, and the second as constants
// problem: has two "types"
// problem: fakeEnum2 has no intellisense in Code, since it is declared as having any properties
type fakeEnumType = 'UP' | 'DOWN'
const fakeEnum2: { [prop: string]: fakeEnumType } = {
Up: 'UP',
one: 'DOWN'
};
const fakeValue = fakeEnum2.Up;
console.log(fakeValue === fakeEnum2.Up);
// newer alternative
const ICON_LEFT = 'left';
const ICON_RIGHT = 'right';
type iconPosition = typeof ICON_LEFT | typeof ICON_RIGHT;
const position1: iconPosition = ICON_LEFT;
const position2: iconPosition = ICON_RIGHT;
const position3: iconPosition = 'left';
// this would fail
// const position4: iconPosition = 'center';
/** Utility function to create a K:V from a list of strings https://basarat.gitbooks.io/typescript/docs/types/literal-types.html */
// problem: cannot have different keys and values (e.g. keys in SNAKE_CASE)
function strEnum<T extends string>(o: T[]): { [K in T]: K } {
return o.reduce((res, key) => {
res[key] = key
return res
}, Object.create(null))
}
const PAYMENT_METHOD = strEnum([
'account',
'card',
'cash'
])
type paymentMethodType = keyof typeof PAYMENT_METHOD
let sample: paymentMethodType
sample = PAYMENT_METHOD.account
sample = 'account'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment