Skip to content

Instantly share code, notes, and snippets.

@pom421
Last active December 29, 2022 12:35
Show Gist options
  • Save pom421/bae67d6b572a20ebc2e97a28e2a3736c to your computer and use it in GitHub Desktop.
Save pom421/bae67d6b572a20ebc2e97a28e2a3736c to your computer and use it in GitHub Desktop.
Cast as a value of a tupe
/**
* Takes a string and returns it as an element of a tuple.
*
* In case of invalid value, returns default value if there is one, otherwise throw an error.
*/
export const castAsTupleOption = <Tuple extends readonly string[]>(
options: Tuple,
value: string | undefined,
defaultValue?: Tuple[number],
): Tuple[number] => {
if (value && options.includes(value)) {
return value as Tuple[number];
} else {
if (defaultValue) return defaultValue;
throw new Error(`The value doesn't match the expected values ${options.join(", ")}`);
}
};
// ex
const colors = ["red", "green", "blue"] as const;
const myColor = castAsTupleOption(colors, "yellow", "red")
console.log("myColor", myColor)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment