首页 > 解决方案 > 如何从 Typescript / Angular 7 中的对象变量中获取类型?

问题描述

我正在尝试从自定义对象实例中获取类型/类。然后,这将用作传递给泛型函数的类型参数,而不仅仅是使用“任何”类型。

我已经尝试过 foo.prototype、Object.getPrototypeOf(foo)、typeof foo、foo.constructor、foo.constructor.name 等,但还没有找到返回对象类型/类本身的方法。下面的示例说明了我想要实现的目标 - 它在这里不起作用,因为 constructor.name 只返回类型的名称:

var vehicle 

if (selected == 'car') { 
vehicle = new Car() 
} else { 
vehicle = new Bike()  
} 

var vehicleType = vehicle.constructor.name

buildVehicle<vehicleType>(vehicle) 

buildVehicle<T>(vehicle:T) { 
    do stuff… 
}

我对打字稿和javascript很陌生,所以我不确定这是否可能,但希望有办法做到这一点。

感谢您对此的任何帮助。

标签: angulartypescript

解决方案


在您的示例中,您根本不应该将类型添加到泛型中。TypeScript 可以在此上下文中推断类型,因为T使用了参数。

// Use it like this: 
buildVehicle(vehicle);

如果你真的想在这里添加泛型,你可以使用typeof.

buildVehicle<typeof vehicle>(vehicle);

在这种情况下,这相当于

buildVehicle<Car | Bike>(vehicle);

因为在编译时无法确定vehicle实际具有哪种类型。它只能在运行时确定。但是由于 TypeScript 类型在转译过程中丢失(因为它转译为 JavaScript),所以没有办法用你当前的代码来做到这一点。

但是,您可以更改代码以使其在编译时可确定。

if (vehicle instanceof Car) {
   buildVehicle<Car>(vehicle); // Vehicle is narrowed down to type "Car"
} else if (vehicle instanceof Bike) { // else would suffice if only 2 possible types
   buildVehicle<Bike>(vehicle); // Vehicle is narrowed down to type "Bike"
}

但是,就您而言,这可能没有多大意义。


推荐阅读