TypeScript type of all JavaScript `typeof` return values - Stack Overflow

admin2025-04-20  0

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;
};
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745123308a286277.html

最新回复(0)