这不可能。
TypeScript 的静态类型系统(其中包括您的myType
定义和类型注释)是erased https://github.com/Microsoft/TypeScript/wiki/FAQ#what-is-type-erasure当代码作为 JavaScript 发出时。 JavaScript 是在运行时实际运行的。在运行时,您可以访问的所有内容是values。类型擦除意味着上面的代码变成这样:
const passingType = (t) => {
const x = {};
};
passingType(myType);
没有指定值myType
传递给passingType
.
而且由于 TypeScript 类型在运行时不作为值存在,因此不存在像您所调用的那样的“类型的类型”Type
。因此,如上所述,这种方法并不是直接可行的。
与其考虑在运行时将“类型”传递给函数(这没有什么成效),不如具体考虑一下您希望在纯 JavaScript 运行时发生什么,然后编写类型来支持它。
您真正想在运行时对“类型”做什么?您想用它来检查值是否属于该类型吗?然后,您可能不想传递类型,而是传递类型保护函数 https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards:
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");
}
}
你可以这样使用它:
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
您的实际用例将推动参数的要求passingType
应该看起来像。它可能是一个完整的数据结构,代表您想要在运行时使用“类型”执行的各种操作。因此,即使这个类型保护示例不适合您,也可能有其他东西可以。
但同样,简短的答案是 TypeScript 的静态类型系统被删除,因此不可能在运行时直接引用其类型。
Playground 代码链接 https://www.typescriptlang.org/play?#code/C4TwDgpgBA4grgQwE4BMA8AVAfFAvFACgA8AuKBAOxAEo8cioBLAZygwG4BYAKAGMB7Cs2BQwCZs0YUA5hnDR8mADRYCwMvGTpstXDgDePKMaYAzQsAJwKKCKakQU1Woe4n3UAUP4AbCADoffmkCACJrW3sKRygASQBlKH5zYAALaGlEVBjQSDZQ6i43EwBfYwgfZmhXDxMvZl8AoJDwmzsHFCZWADkAeQwklPSoTK0c+XzCo1KoHhKeHlNrXmBGQS6AVTaox2IyShoyBhYoCPbozpqTJAhgOCQKKFyIZKgGXA+oVsiO0KL57g8MQSKSyeQEFhbH4XQpQAD0cNO2w6cUSrzSGSytk6zzYC24SwoKzWjxY3TgAFsAEYQJB7chUahHLpQCiUmlIKBXYw3O4PJ7yV7vT6hNnU2l-OZA8SSGRySAQ5jk8VIWEIpHQmIJKB9Abo4ajbI4iYYfGE4nrMns2m9JBQ867UgMw5vFlijlQAA+Godl2mPNu91JSutdKItE93shyIuxCm3AB0pBcvBVpVtvtOyc7HhiLOWdRgyeBqx4zypsB3CAA