Last active
June 9, 2022 14:06
-
-
Save mxdvl/2e5fa0562b35a4fc9d18dcd5ac791b0f to your computer and use it in GitHub Desktop.
Type definitions in TS + JS
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
// the options array exported if you want to loop over the options | |
const options = ["a", "b", "c"] as const; | |
// the type which as no runtime overhead at all | |
type Option = typeof options[number]; // "a" | "b" | "c" | |
// the predicate for filtering or other runtime checks | |
const isOption = (option: string): option is Option => | |
(options).includes(option as Option) | |
// Parse, don’t validate | |
const getOption = (option: string): Option => { | |
if (isOption(option)) return option; | |
throw new Error(`Invalid option "${option}". Should be one of [${options.join(", ")}].`); | |
} | |
export { options, isOption, getOption } | |
export type { Option } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment