Skip to content

Instantly share code, notes, and snippets.

@alaindet
Last active November 14, 2023 14:22
Show Gist options
  • Save alaindet/86bf36b4549859c59e9f59f476dba9e5 to your computer and use it in GitHub Desktop.
Save alaindet/86bf36b4549859c59e9f59f476dba9e5 to your computer and use it in GitHub Desktop.
TypeScript better enums
//
// Thanks to Matt Pocock's video "Enums considered harmful"
// https://www.youtube.com/watch?v=jjMbPt_H3RQ
//
// Please note that enums per se are great in any language,
// but TypeScript's enums are implemented in a convoluted and verbose way (as of version 4.9)
// since JavaScript (as of ES2022) does not natively support enums
//
// This can be moved elsewhere
type EnumLike<T> = T[keyof T];
// "as const" turns this into a readonly, "real" constant
const LOG_LEVEL = {
DEBUG: 'DEBUG',
WARNING: 'WARNING',
ERROR: 'ERROR',
} as const;
// This is the associated type of the readonly constant
// In case you want to use it as a type
type LogLevel = EnumLike<typeof LOG_LEVEL>
// Example function using the LogLevel associated type
function logMe(level: LogLevel, message: string): void {
// ...
}
// Example usage of the example function
logMe('DEBUG', 'It works with literals');
logMe(LOG_LEVEL.DEBUG, 'As well as enum-like access');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment