Skip to content

Instantly share code, notes, and snippets.

@Elijah-Bodden
Last active August 27, 2022 00:17
Show Gist options
  • Save Elijah-Bodden/fe846be3c0895fa26099b5293bdbc81b to your computer and use it in GitHub Desktop.
Save Elijah-Bodden/fe846be3c0895fa26099b5293bdbc81b to your computer and use it in GitHub Desktop.
A tiny, dynamic type checker and TypeError generator
function checkTypes(...requiredArgs, expectedTypes) {
var mistyped = requiredArgs.filter((argumentObj, index) => {
return expectedTypes[index]
? !expectedTypes[index].includes(typeof Object.values(argumentObj)[0])
: false;
});
if (mistyped != "") {
throw new TypeError(
`expected the argument "${
Object.keys(mistyped[0])[0]
}" to be of one of the following types: ${expectedTypes[
requiredArgs
.map((obj) => {
return Object.keys(obj)[0];
})
.indexOf(Object.keys(mistyped[0])[0])
].reduce((previous, current, index, array) => {
return (
previous +
current +
(array.length > 1 && index !== array.length - 1
? index === array.length - 2
? ", or "
: ", "
: "")
);
}, "")}; got ${typeof Object.values(mistyped[0])[0]}`
);
}
}
@Elijah-Bodden
Copy link
Author

Elijah-Bodden commented Aug 13, 2022

Simply pass each variable you wish to check, one at a time, as its reference wrapped by braces. Finally, provide an array of arrays, each sub-array corresponding to one passed variable, and containing every type which that variable's value is allowed to take. If one of the variables is of a type not specified for it, a TypeError will be thrown. If multiple variables are invalid, the first one, in the order that they were passed, will be the one mentioned in the Error.

(This function was taken directly from the code of the Membrane project.)

//Example use-case

const x = "I'm a string."
const y = 8092834
const z = undefined
try {
  checkTypes({x}, {y}, {z}, [["string", "number"], ["number"], ["string", "object", "bigint"]])
} catch (error) {
  //Expected output: "TypeError: expected the argument "z" to be of one of the following types: string, object, or bigint; got undefined"
  console.warn(error)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment