I'm working on a function to validate function parameters in embedded untyped JavaScript in an input stream for a TypeScript system something like a templating engine.
const javaScriptType = (untyped: unknown) => typeof untyped;
type JavaScriptType = ReturnType<typeof javaScriptType>;
So JavaScriptType
ends up being:
type JavaScriptType = "string" | "number"
| "bigint" | "boolean" | "symbol"
| "undefined" | "object" | "function";
But, using my method, I end up with the "useless" function javaScriptType
which only exists to enable me to use ReturnType
to get the results I want.
Is there an easier way I can do this without "wasting" a function?
The simple answer would just to hard code the expected values... it's not like JavaScript's typeof
operator is going to change anytime soon... but hard coded values feel, somehow, "dirty".
Just to clarify, this type will be used something like this:
const failedTypes = (
parameters: Array<unknown>, allowedTypes: Array<JavaScriptType>
): => {
const failed: Array<string> = [];
for (const [index, parameter] of parameters.entries()) {
const typeOf = typeof parameter;
if (!allowedTypes.includes(typeOf)) {
failed.push(`${index}: ${typeOf}`);
}
}
return failed;
};