4 ms·
We alway use this in place of ENUMs: export const SMS_TYPE = { BULK: 'bulk', MARKETING: 'marketing', PIN: 'pin', SIGNUP: 's
by joshstrange 2y ago
We alway use this in place of ENUMs:
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.
- ralusek 2y agoExactly what I do, but I've found that I almost always will add a few things that come in handy. 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];
- joshstrange 2y agoNice, I will have to watch for cases where I could make use of that! 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.
- ralusek 2y agoI end up using the sets a lot in particular for any case where you're dealing with unvalidated data. Type checks where you need to say, for example, SMS_TYPE_SET.has(someValue)
- recursive 2y agoYou can simplify the `SmsType` declaration a bit. export type SmsType = typeof SMS_TYPE_LIST[number];
- sirlone 2y agowhy repeat the names? // 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;