4 ms·
If the strings are static you can define a type that's a union of string literals, create a tuple containing them all, and then a type guard function that simpl
by samhh 7y ago
If the strings are static you can define a type that's a union of string literals, create a tuple containing them all, and then a type guard function that simply checks the argument against the array. If the strings are dynamic then you're better off looking at a library like newtype-ts, but it's not very ergonomic compared to the likes of Haskell/PureScript so use sparingly.
- no_wizard 7y agoWhy not just use an Enum? It will only accept the values of that enum. https://www.typescriptlang.org/docs/handbook/enums.html#enums https://www.typescriptlang.org/docs/handbook/enums.html#enum... https://www.typescriptlang.org/play/index.html?useDefineForClassFields=true&preserveConstEnums=true#code/KYOwrgtgBAsgngZQC4CcCWIDmBnKBvAWACgpSoAxAeUqgF4oAiAIwEMUGAaYsqAIQEEASnUYAzAPbjO3MlUoDh9BhPGt2xAL7FiosCADGSNOJBQTAGzgBRcBH4pMACgBuLcwC5YiVBhwBKfBlSfRNscXNgADpzcScGJAALNFwAdzRzczMQSygkFgBrYCyi8VFchKLCuFxRFHFoeGR0LGwGPwBuIKgQkDCI6NiXNzpaekafFsiFDs1tIgtrW3s4xOSoNIyoJiKWU2AUOvYZ+ezFyGXHceacKaEAgHpHqAAVJNw1kHEkKF2ofcOgA https://www.typescriptlang.org/play/index.html?useDefineForC...
- untog 7y agoJust my personal preference but using these string union types means that you don’t have to import the enum. Plus it’s less verbose and translates back to JS better than an enum does. Really just a matter of preference though.