簡體   English   中英

如何從Typescript / Angular 7中的對象變量獲取類型?

[英]How do I get the type from an object variable in Typescript / Angular 7?

我正在嘗試從自定義對象實例獲取類型/類。 然后,它將用作傳遞給泛型函數的類型參數,而不僅僅是使用“ any”類型。

我嘗試了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還是很陌生,所以我不確定這是否可能,但是希望有一種方法可以做到。

感謝您對此的任何幫助。

嘗試使用工會類型: type Vehicle = Bike | Car; type Vehicle = Bike | Car;

在您的示例中,您根本不應將類型添加到泛型中。 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"
}

不過,就您而言,這可能沒有多大意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM