It is simply not feasible.
When TypeScript code is converted to JavaScript for execution, the static type system, including your myType
definition and type annotations, is essentially removed. At runtime, only values are accessible, not types. This means that your code transforms into something like this:
const passingType = (t) => {
const x = {};
};
passingType(myType);
Since TypeScript types do not exist as values during runtime, there is no concept of a "type of types" like what you referred to as Type
. Therefore, achieving this directly is not possible as stated.
Rather than attempting to pass a "type" to a function at runtime, which is ineffective, it's more effective to focus on defining what actions you want to take in pure JavaScript at runtime and then create types to support those actions.
What specific purpose do you intend to achieve with a "type" at runtime? Would you like to use it to verify if a value matches that type? In that case, instead of passing a type, consider passing a type guard function:
type Guard<T> = (x: any) => x is T;
const passingType = <T,>(t: Guard<T>) => {
if (t(undefined)) {
console.log("undefined IS of the guarded type T");
} else {
console.log("undefined is NOT of the guarded type T");
}
}
This can be used as shown below:
function isUndefined(x: any): x is undefined {
return typeof x === "undefined";
}
passingType(isUndefined); // undefined IS of the guarded type T
function isNumber(x: any): x is number {
return typeof x === "number";
}
passingType(isNumber); // undefined IS NOT of the guarded type T
function isNumberOrUndefined(x: any): x is number | undefined {
return isNumber(x) || isUndefined(x);
}
passingType(isNumberOrUndefined); // undefined IS of the guarded type T
Your specific requirements will determine the structure of the argument for passingType
. It might involve an entire data structure representing various actions you wish to perform with a "type" at runtime. If the type guard example does not suit your needs, another approach may work better.
In conclusion, TypeScript's static type system is removed during compilation, making it impossible to reference its types directly during runtime.
Link to interactive code sample