Last active
September 26, 2025 05:35
-
-
Save erkobridee/576bcba33ed5fcf26c68fb0f32efdef3 to your computer and use it in GitHub Desktop.
a sample code of how to use const as const instead of enums in TypeScript
This file contains hidden or 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
| /* | |
| from: | |
| Enums considered harmful | Matt Pocock | |
| https://www.youtube.com/watch?v=jjMbPt_H3RQ | |
| */ | |
| const LogLevel = { | |
| DEBUG: "DEBUG", | |
| INFO: "INFO", | |
| WARNING: "WARNING", | |
| ERROR: "ERROR" | |
| } as const; | |
| type TLogLevelKeys = keyof typeof LogLevel; | |
| type TLogLevel = typeof LogLevel[TLogLevelKeys]; | |
| const log = (message: string, level: TLogLevel = LogLevel.DEBUG) => console.log(`${LogLevel[level]}: ${message}`); | |
| log("DEBUG value from const", LogLevel.DEBUG); | |
| //---------------------------------------------// | |
| enum ELogLevel { | |
| DEBUG = "DEBUG", | |
| INFO = "INFO", | |
| WARNING = "WARNING", | |
| ERROR = "ERROR" | |
| } | |
| console.log("DEBUG value from enum", ELogLevel.DEBUG); |
Author
Author
Sandro Maglione on X: "satisfies makes everything type safe in typescript Combine it with union types and template literals to stop worrying about typos ever again 🥳 https://t.co/n2FBALhlzv" / X
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sandro Maglione on X: "Typescript wizardy:
as const+satisfiesCombine both to have type safety on Record keys and values + constant inferred types You can then extract both keys and values as unions usingkeyofandtypeof🧙 https://t.co/cUH05nNXl2" / X