Last active
August 27, 2022 00:17
-
-
Save Elijah-Bodden/fe846be3c0895fa26099b5293bdbc81b to your computer and use it in GitHub Desktop.
A tiny, dynamic type checker and TypeError generator
This file contains 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
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]}` | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.)