[英]How do I get the type from an object variable in Typescript / Angular 7?
I'm trying to get the type/class from an custom object instance. 我正在尝试从自定义对象实例获取类型/类。 This will then be used as a type parameter passed to a generic function rather than just use the 'any' type.
然后,它将用作传递给泛型函数的类型参数,而不仅仅是使用“ any”类型。
I've tried foo.prototype, Object.getPrototypeOf(foo), typeof foo, foo.constructor, foo.constructor.name etc but haven't yet found a way to return the objects's type/class itself. 我尝试了foo.prototype,Object.getPrototypeOf(foo),typeof foo,foo.constructor,foo.constructor.name等,但是还没有找到一种方法来返回对象的类型/类本身。 The example below gives an idea of what I want to achieve - it doesn't work here because constructor.name only returns the name of the type:
下面的示例给出了我想要实现的目标的想法-在这里不起作用,因为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…
}
I'm pretty new to typescript and javascript so I'm not sure this is even possible, but hopefully there is a way to do this. 我对于打字稿和JavaScript还是很陌生,所以我不确定这是否可能,但是希望有一种方法可以做到。
Thanks for any help on this. 感谢您对此的任何帮助。
Try to use type union: type Vehicle = Bike | Car;
尝试使用工会类型:
type Vehicle = Bike | Car;
type Vehicle = Bike | Car;
In your example you shouldn't add the type to the generic at all. 在您的示例中,您根本不应将类型添加到泛型中。 TypeScript can infer the type in this context, because
T
is used a parameter. TypeScript可以在这种情况下推断类型,因为
T
被用作参数。
// Use it like this:
buildVehicle(vehicle);
If you really want to add the generic here, you could use typeof
. 如果您真的想在此处添加泛型,则可以使用
typeof
。
buildVehicle<typeof vehicle>(vehicle);
This is, in this case, equivalent to 在这种情况下,这相当于
buildVehicle<Car | Bike>(vehicle);
because it is not possible to determine which type vehicle
actually has at compile time . 因为无法确定编译时
vehicle
实际拥有的类型。 It could only be determined at runtime . 它只能在运行时确定。 But since TypeScript types are lost during transpilation (as it transpiles to JavaScript), there is no way to do that with your current code.
但是,由于TypeScript类型在转换过程中会丢失(因为它会转换为JavaScript),因此无法使用当前代码来执行此操作。
You could, however, change your code to make it determinable at compile time . 但是,您可以更改代码以使其在编译时可以确定。
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"
}
Though, in your case, this would probably not make much sense. 不过,就您而言,这可能没有多大意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.