Last active
December 29, 2022 12:35
-
-
Save pom421/bae67d6b572a20ebc2e97a28e2a3736c to your computer and use it in GitHub Desktop.
Cast as a value of a tupe
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
/** | |
* 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