Skip to content

Instantly share code, notes, and snippets.

@mxdvl
Last active June 9, 2022 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxdvl/2e5fa0562b35a4fc9d18dcd5ac791b0f to your computer and use it in GitHub Desktop.
Save mxdvl/2e5fa0562b35a4fc9d18dcd5ac791b0f to your computer and use it in GitHub Desktop.
Type definitions in TS + JS
// 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