by joshstrange · 1y ago · 0 comments
export const SMS_TYPE = {
BULK: 'bulk',
MARKETING: 'marketing',
PIN: 'pin',
SIGNUP: 'signup',
TRANSACTION: 'transaction',
TEST: 'test',
} as const;
export type SmsType = typeof SMS_TYPE[keyof typeof SMS_TYPE];
ENUMs (at least in my experience, which may be dated) had a number of drawbacks that pushed us to this format. I vaguely remember having issues parsing data from the server and/or sending ENUM values to the server but it's been a long time and I've been using this const pattern for around 5 years or so now. export const SMS_TYPE = Object.freeze({
BULK: 'bulk',
MARKETING: 'marketing',
PIN: 'pin',
SIGNUP: 'signup',
TRANSACTION: 'transaction',
TEST: 'test',
} as const);
export const SMS_TYPE_LIST = Object.freeze(Object.values(SMS_TYPE));
export const SMS_TYPE_SET = Object.freeze(new Set(SMS_TYPE_LIST));
export type SmsType = typeof SMS_TYPE[keyof typeof SMS_TYPE]; export type SmsType = typeof SMS_TYPE_LIST[number];I think I originally found the const-style on somewhere HN or SO but it has changed a bit over the years due to suggestions people have made so thank you for contributing to improvement of this pattern for me.
Type checks where you need to say, for example, SMS_TYPE_SET.has(someValue)
// put this in some util.ts or enum.ts file
function makeEnum<T extends readonly string[]>(keys: T) {
return Object.fromEntries(keys.map((x) => [x, x])) as {
[K in (typeof keys)[number]]: K
};
}
const SMS_TYPES = makeEnum(['bulk', 'marketing', 'pin', 'signup', 'transaction', 'test'] as const);
type SMS_TYPE = keyof typeof SMS_TYPES;